import { Form, Head, Link } from '@inertiajs/react';
import { FileText } from 'lucide-react';
import FinancingController from '@/actions/App/Http/Controllers/FinancingController';
import InputError from '@/components/input-error';
import {
    FinancingStatusBadge,
    InstalmentTable,
} from '@/components/member/financing-status';
import MemberPage from '@/components/member/member-page';
import ProgressBar from '@/components/member/progress-bar';
import { Button } from '@/components/ui/button';
import { formatDate, formatNaira } from '@/lib/format';
import { index, statement } from '@/routes/financing';
import { edit as editPin } from '@/routes/transaction-pin';
import type { FinancingItem, InstalmentItem } from '@/types';
import { RequiredMark } from '@/components/required-mark';

export default function FinancingShow({
    financing,
    instalments,
    nextInstalment,
    amountRepaid,
    walletBalance,
    hasPin,
}: {
    financing: FinancingItem;
    instalments: InstalmentItem[];
    nextInstalment: InstalmentItem | null;
    amountRepaid: number;
    walletBalance: number;
    hasPin: boolean;
}) {
    const total = financing.totalRepayable ?? 0;
    const progress = total > 0 ? Math.floor((amountRepaid / total) * 100) : 0;

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

            <MemberPage
                title={financing.typeLabel}
                description={`${financing.reference} · applied ${formatDate(financing.appliedAt)}`}
                actions={<FinancingStatusBadge financing={financing} />}
            >
                {financing.status === 'active' ||
                financing.status === 'completed' ? (
                    <div className="grid gap-4 lg:grid-cols-3">
                        <section className="rounded-landing-lg bg-brand-dark p-6 text-white lg:col-span-2">
                            <p className="text-sm text-white/70">Repaid</p>
                            <p className="mt-2 font-display text-3xl font-semibold tabular-nums">
                                {formatNaira(amountRepaid)}
                                <span className="ml-2 font-body text-sm font-medium text-white/70">
                                    of {formatNaira(total)}
                                </span>
                            </p>
                            <div className="mt-4 [&>div]:bg-white/15">
                                <ProgressBar
                                    value={progress}
                                    label="Repayment progress"
                                />
                            </div>
                            <dl className="mt-5 grid grid-cols-2 gap-3 text-sm">
                                <div>
                                    <dt className="text-white/60">Paid out</dt>
                                    <dd className="font-semibold">
                                        {formatNaira(
                                            financing.approvedAmount ?? 0,
                                        )}
                                    </dd>
                                </div>
                                <div>
                                    <dt className="text-white/60">Term</dt>
                                    <dd className="font-semibold">
                                        {financing.tenorMonths} months
                                    </dd>
                                </div>
                            </dl>
                        </section>

                        <section className="rounded-landing-lg border border-surface-200 bg-white p-5">
                            {nextInstalment ? (
                                <>
                                    <h2 className="font-semibold text-ink">
                                        Next repayment
                                    </h2>
                                    <p className="mt-1 font-display text-2xl font-semibold text-ink tabular-nums">
                                        {formatNaira(nextInstalment.amount)}
                                    </p>
                                    <p
                                        className={
                                            nextInstalment.state === 'overdue'
                                                ? 'text-sm text-red-700'
                                                : 'text-sm text-ink-500'
                                        }
                                    >
                                        {nextInstalment.state === 'overdue'
                                            ? 'Overdue since '
                                            : 'Due '}
                                        {formatDate(nextInstalment.dueDate)}
                                    </p>
                                    <p className="mt-3 text-xs text-ink-400">
                                        Wallet balance:{' '}
                                        {formatNaira(walletBalance)}
                                    </p>
                                    {hasPin ? (
                                        <Form
                                            {...FinancingController.repay.form(
                                                financing.id,
                                            )}
                                            resetOnSuccess
                                            options={{ preserveScroll: true }}
                                            className="mt-3 grid gap-2"
                                        >
                                            {({ processing, errors }) => (
                                                <>
                                                    <label
                                                        htmlFor="pin"
                                                        className="text-xs font-semibold text-ink-500"
                                                    >
                                                        Transaction PIN
                                                        <RequiredMark />
                                                    </label>
                                                    <div className="flex gap-2">
                                                        <input
                                                            id="pin"
                                                            name="pin"
                                                            type="password"
                                                            inputMode="numeric"
                                                            pattern="[0-9]{4}"
                                                            maxLength={4}
                                                            required
                                                            autoComplete="off"
                                                            className="h-10 w-28 rounded-md border border-input bg-white px-3 text-sm tracking-[0.4em] outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15"
                                                        />
                                                        <Button
                                                            disabled={
                                                                processing
                                                            }
                                                        >
                                                            Pay now
                                                        </Button>
                                                    </div>
                                                    <InputError
                                                        message={errors.pin}
                                                    />
                                                </>
                                            )}
                                        </Form>
                                    ) : (
                                        <p className="mt-3 text-sm text-ink-500">
                                            <Link
                                                href={editPin()}
                                                className="font-semibold text-brand hover:text-highlight-dark"
                                            >
                                                Set your transaction PIN
                                            </Link>{' '}
                                            to make repayments.
                                        </p>
                                    )}
                                </>
                            ) : (
                                <>
                                    <h2 className="font-semibold text-ink">
                                        All repaid
                                    </h2>
                                    <p className="mt-1 text-sm text-ink-500">
                                        Thank you — this facility is fully
                                        repaid.
                                    </p>
                                </>
                            )}
                        </section>
                    </div>
                ) : (
                    <section className="rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                        <dl className="grid gap-3 text-sm sm:grid-cols-2">
                            <div>
                                <dt className="text-ink-400">
                                    Amount requested
                                </dt>
                                <dd className="font-semibold text-ink">
                                    {formatNaira(financing.amountRequested)}
                                </dd>
                            </div>
                            <div>
                                <dt className="text-ink-400">Repay over</dt>
                                <dd className="font-semibold text-ink">
                                    {financing.tenorMonths} months
                                </dd>
                            </div>
                        </dl>
                        {financing.decisionNote && (
                            <p className="mt-4 rounded-md bg-surface-50 px-4 py-3 text-sm text-ink-700">
                                {financing.decisionNote}
                            </p>
                        )}
                        {financing.status === 'pending' && (
                            <div className="mt-4 flex flex-wrap items-center gap-3">
                                <p className="text-sm text-ink-500">
                                    We're reviewing your application and will
                                    notify you of the decision.
                                </p>
                                <Form
                                    {...FinancingController.cancel.form(
                                        financing.id,
                                    )}
                                >
                                    {({ processing }) => (
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            disabled={processing}
                                        >
                                            Cancel application
                                        </Button>
                                    )}
                                </Form>
                            </div>
                        )}
                    </section>
                )}

                <section className="rounded-landing-lg border border-surface-200 bg-white p-5">
                    <h2 className="font-semibold text-ink">Purpose</h2>
                    <p className="mt-1 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" />
                        Bank statement you uploaded
                    </a>
                </section>

                {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>
        </>
    );
}

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