import { Form, Head } from '@inertiajs/react';
import { FileText } from 'lucide-react';
import FinancingReviewController from '@/actions/App/Http/Controllers/Admin/FinancingReviewController';
import InputError from '@/components/input-error';
import {
    FinancingStatusBadge,
    InstalmentTable,
} from '@/components/member/financing-status';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { formatDate, formatNaira } from '@/lib/format';
import { index } from '@/routes/admin/financing';
import { statement } from '@/routes/financing';
import type { FinancingItem, InstalmentItem } from '@/types';

type AdminFinancing = FinancingItem & {
    guarantorName: string;
    guarantorPhone: string;
    allowsMarkup: boolean;
    member: {
        name: string;
        email: string;
        phone: string | null;
        kycStatus: string;
        previousFinancings: number;
    };
};

const textareaClasses =
    'rounded-md border border-input bg-white px-3 py-2 text-sm outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15';

export default function AdminFinancingShow({
    financing,
    instalments,
    tenors,
    canDecide,
}: {
    financing: AdminFinancing;
    instalments: InstalmentItem[];
    tenors: number[];
    canDecide: boolean;
}) {
    const nairaDefault = (kobo: number) =>
        (kobo / 100).toFixed(2).replace(/\.00$/, '');

    return (
        <>
            <Head title={`Review ${financing.reference}`} />

            <MemberPage
                title={`${financing.member.name} · ${formatNaira(financing.amountRequested)}`}
                description={`${financing.typeLabel} · ${financing.reference} · applied ${formatDate(financing.appliedAt)}`}
                actions={<FinancingStatusBadge financing={financing} />}
            >
                <div className="grid gap-4 lg:grid-cols-2">
                    <section className="rounded-landing-lg border border-surface-200 bg-white p-5">
                        <h2 className="font-semibold text-ink">Application</h2>
                        <dl className="mt-3 grid grid-cols-2 gap-3 text-sm">
                            {[
                                [
                                    'Requested',
                                    formatNaira(financing.amountRequested),
                                ],
                                ['Term', `${financing.tenorMonths} months`],
                                [
                                    'Monthly income',
                                    formatNaira(financing.monthlyIncome),
                                ],
                                [
                                    'Even instalment',
                                    formatNaira(
                                        Math.ceil(
                                            financing.amountRequested /
                                                financing.tenorMonths,
                                        ),
                                    ),
                                ],
                                ['Guarantor', financing.guarantorName],
                                ['Guarantor phone', financing.guarantorPhone],
                            ].map(([term, detail]) => (
                                <div key={term}>
                                    <dt className="text-xs text-ink-400">
                                        {term}
                                    </dt>
                                    <dd className="font-medium text-ink">
                                        {detail}
                                    </dd>
                                </div>
                            ))}
                        </dl>
                        <p className="mt-4 text-sm whitespace-pre-line text-ink-700">
                            {financing.purpose}
                        </p>
                        <a
                            href={statement.url(financing.id)}
                            target="_blank"
                            rel="noopener"
                            className="mt-3 inline-flex items-center gap-1.5 text-sm font-semibold text-brand hover:text-highlight-dark"
                        >
                            <FileText className="size-4" />
                            Open bank statement
                        </a>
                    </section>

                    <section className="rounded-landing-lg border border-surface-200 bg-white p-5">
                        <h2 className="font-semibold text-ink">Member</h2>
                        <dl className="mt-3 grid grid-cols-2 gap-3 text-sm">
                            {[
                                ['Email', financing.member.email],
                                ['Phone', financing.member.phone ?? '—'],
                                ['Verification', financing.member.kycStatus],
                                [
                                    'Previous financing',
                                    String(financing.member.previousFinancings),
                                ],
                            ].map(([term, detail]) => (
                                <div key={term}>
                                    <dt className="text-xs text-ink-400">
                                        {term}
                                    </dt>
                                    <dd className="font-medium break-all text-ink">
                                        {detail}
                                    </dd>
                                </div>
                            ))}
                        </dl>
                    </section>
                </div>

                {financing.status === 'pending' && !canDecide ? (
                    <p className="rounded-landing-lg border border-surface-200 bg-white px-5 py-4 text-sm text-ink-500">
                        This application is waiting for a decision. Only staff
                        who can approve loans, and who did not apply themselves,
                        can approve or decline it.
                    </p>
                ) : financing.status === 'pending' ? (
                    <div className="grid gap-4 lg:grid-cols-2">
                        <Form
                            {...FinancingReviewController.approve.form(
                                financing.id,
                            )}
                            className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5"
                        >
                            {({ processing, errors }) => (
                                <>
                                    <h2 className="font-semibold text-ink">
                                        Approve and pay out
                                    </h2>
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <div className="grid gap-2">
                                            <Label
                                                htmlFor="approved_amount"
                                                required
                                            >
                                                Amount to pay out
                                            </Label>
                                            <NairaInput
                                                id="approved_amount"
                                                name="approved_amount"
                                                required
                                                defaultValue={nairaDefault(
                                                    financing.amountRequested,
                                                )}
                                            />
                                            <InputError
                                                message={errors.approved_amount}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label
                                                htmlFor="total_repayable"
                                                required
                                            >
                                                Total repayable
                                            </Label>
                                            <NairaInput
                                                id="total_repayable"
                                                name="total_repayable"
                                                required
                                                defaultValue={nairaDefault(
                                                    financing.amountRequested,
                                                )}
                                            />
                                            <InputError
                                                message={errors.total_repayable}
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="tenor_months">
                                                Term
                                            </Label>
                                            <select
                                                id="tenor_months"
                                                name="tenor_months"
                                                defaultValue={
                                                    financing.tenorMonths
                                                }
                                                className="h-10 rounded-md border border-input bg-white px-3 text-sm"
                                            >
                                                {tenors.map((months) => (
                                                    <option
                                                        key={months}
                                                        value={months}
                                                    >
                                                        {months} months
                                                    </option>
                                                ))}
                                            </select>
                                            <InputError
                                                message={errors.tenor_months}
                                            />
                                        </div>
                                    </div>
                                    <p className="text-xs text-ink-400">
                                        {financing.allowsMarkup
                                            ? 'Total repayable = agreed sale price / rent / profit share. It must be at least the payout.'
                                            : 'This type is repaid at exactly the payout: total repayable must equal it.'}
                                    </p>
                                    <div className="grid gap-2">
                                        <Label htmlFor="approve-note">
                                            Note to member (optional)
                                        </Label>
                                        <textarea
                                            id="approve-note"
                                            name="note"
                                            rows={2}
                                            maxLength={1000}
                                            className={textareaClasses}
                                        />
                                        <InputError message={errors.note} />
                                    </div>
                                    <div>
                                        <Button disabled={processing}>
                                            Approve and pay out
                                        </Button>
                                    </div>
                                </>
                            )}
                        </Form>

                        <Form
                            {...FinancingReviewController.decline.form(
                                financing.id,
                            )}
                            className="grid content-start gap-4 rounded-landing-lg border border-surface-200 bg-white p-5"
                        >
                            {({ processing, errors }) => (
                                <>
                                    <h2 className="font-semibold text-ink">
                                        Decline
                                    </h2>
                                    <div className="grid gap-2">
                                        <Label htmlFor="decline-note" required>
                                            Reason the member will see
                                        </Label>
                                        <textarea
                                            id="decline-note"
                                            name="note"
                                            required
                                            minLength={10}
                                            rows={4}
                                            maxLength={1000}
                                            className={textareaClasses}
                                        />
                                        <InputError message={errors.note} />
                                    </div>
                                    <div>
                                        <Button
                                            variant="destructive"
                                            disabled={processing}
                                        >
                                            Decline application
                                        </Button>
                                    </div>
                                </>
                            )}
                        </Form>
                    </div>
                ) : (
                    financing.decisionNote && (
                        <p className="rounded-landing-lg border border-surface-200 bg-white px-5 py-4 text-sm text-ink-700">
                            Decision note: {financing.decisionNote}
                        </p>
                    )
                )}

                {instalments.length > 0 && (
                    <section className="overflow-hidden rounded-landing-lg border border-surface-200 bg-white">
                        <h2 className="px-5 py-4 font-display text-lg font-semibold text-ink">
                            Repayment schedule
                        </h2>
                        <div className="border-t border-surface-100">
                            <InstalmentTable instalments={instalments} />
                        </div>
                    </section>
                )}
            </MemberPage>
        </>
    );
}

AdminFinancingShow.layout = {
    breadcrumbs: [{ title: 'Financing review', href: index() }],
};
