import { Head, Link } from '@inertiajs/react';
import {
    ArrowRight,
    Check,
    CircleAlert,
    HandHeart,
    KeyRound,
    ShoppingBag,
    X,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useMemo, useState } from 'react';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import { formatDate, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { calculator, create, index } from '@/routes/financing';
import { show as kycShow } from '@/routes/kyc';
import { edit as editPin } from '@/routes/transaction-pin';
import type { FinancingTypeOption } from '@/types';

type Eligibility = {
    isVerified: boolean;
    hasPin: boolean;
    hasOpenFinancing: boolean;
};

/** Instalments should stay under a third of monthly income. */
const AFFORDABLE_SHARE = 33;

const quickAmounts = [50_000, 100_000, 300_000, 500_000, 1_000_000];

/** Help repaid exactly as borrowed gets a different icon from priced financing. */
function typeIcon(option: FinancingTypeOption): LucideIcon {
    return option.allowsMarkup ? ShoppingBag : HandHeart;
}

const cardClasses =
    'rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm';

function toKobo(naira: string): number | null {
    if (!/^\d{1,10}(\.\d{1,2})?$/.test(naira)) {
        return null;
    }

    const [whole, fraction = ''] = naira.split('.');

    return Number(whole) * 100 + Number(fraction.padEnd(2, '0'));
}

function addMonths(date: Date, months: number): Date {
    const result = new Date(date);
    const day = result.getDate();
    result.setDate(1);
    result.setMonth(result.getMonth() + months);
    const lastDay = new Date(
        result.getFullYear(),
        result.getMonth() + 1,
        0,
    ).getDate();
    result.setDate(Math.min(day, lastDay));

    return result;
}

function isoDate(date: Date): string {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

/** Equal instalments with any remainder on the last one, as on approval. */
function buildSchedule(totalKobo: number, months: number) {
    const base = Math.floor(totalKobo / months);
    const remainder = totalKobo - base * months;
    const start = new Date();
    let remaining = totalKobo;

    return Array.from({ length: months }, (_, index) => {
        const amount = base + (index === months - 1 ? remainder : 0);
        remaining -= amount;

        return {
            number: index + 1,
            dueDate: isoDate(addMonths(start, index + 1)),
            amount,
            remaining,
        };
    });
}

export default function FinancingCalculator({
    types,
    tenors,
    limits,
    eligibility,
}: {
    types: FinancingTypeOption[];
    tenors: number[];
    limits: { minAmount: number; maxAmount: number };
    eligibility: Eligibility;
}) {
    const [amount, setAmount] = useState('300000');
    const [tenor, setTenor] = useState(tenors.includes(12) ? 12 : tenors[0]);
    const [income, setIncome] = useState('');
    const [type, setType] = useState(types[0]?.value ?? '');
    const [showTable, setShowTable] = useState(false);

    const amountKobo = toKobo(amount);
    const incomeKobo = toKobo(income);
    const amountProblem =
        amount === ''
            ? 'Enter the amount you need.'
            : amountKobo === null
              ? 'Enter an amount in naira, e.g. 300000.'
              : amountKobo < limits.minAmount * 100
                ? `The smallest amount is ${formatNaira(limits.minAmount * 100)}.`
                : amountKobo > limits.maxAmount * 100
                  ? `The largest amount is ${formatNaira(limits.maxAmount * 100)}.`
                  : null;

    const schedule = useMemo(
        () =>
            amountKobo !== null && amountProblem === null
                ? buildSchedule(amountKobo, tenor)
                : [],
        [amountKobo, amountProblem, tenor],
    );

    const monthly = schedule[0]?.amount ?? null;
    const share =
        monthly !== null && incomeKobo !== null && incomeKobo > 0
            ? Math.round((monthly / incomeKobo) * 100)
            : null;
    const shareTone =
        share === null
            ? 'neutral'
            : share <= 25
              ? 'good'
              : share <= AFFORDABLE_SHARE
                ? 'ok'
                : 'high';
    const peak = Math.max(1, ...schedule.map((row) => row.amount));
    const selectedType = types.find((option) => option.value === type);
    const repaidAsBorrowed = selectedType ? !selectedType.allowsMarkup : false;

    const checklist: {
        label: string;
        state: 'pass' | 'fail' | 'unknown';
        hint?: { text: string; href: ReturnType<typeof kycShow> };
    }[] = [
        {
            label: 'Identity verified',
            state: eligibility.isVerified ? 'pass' : 'fail',
            hint: eligibility.isVerified
                ? undefined
                : { text: 'Verify now', href: kycShow() },
        },
        {
            label: 'Transaction PIN set (needed for repayments)',
            state: eligibility.hasPin ? 'pass' : 'fail',
            hint: eligibility.hasPin
                ? undefined
                : { text: 'Set PIN', href: editPin() },
        },
        {
            label: 'No other financing open',
            state: eligibility.hasOpenFinancing ? 'fail' : 'pass',
            hint: eligibility.hasOpenFinancing
                ? { text: 'View financing', href: index() }
                : undefined,
        },
        {
            label: 'Instalment under a third of income',
            state:
                share === null
                    ? 'unknown'
                    : share <= AFFORDABLE_SHARE
                      ? 'pass'
                      : 'fail',
        },
    ];

    const canApply = eligibility.isVerified && !eligibility.hasOpenFinancing;
    const applyHref = create({
        query: {
            type,
            amount: amountProblem === null ? amount : undefined,
            tenor: String(tenor),
            income: incomeKobo !== null ? income : undefined,
        },
    });

    return (
        <>
            <Head title="Financing calculator" />

            <MemberPage
                title="Financing calculator"
                description="Estimate your monthly repayments before you apply."
            >
                <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,22rem)] lg:items-start">
                    <div className="flex min-w-0 flex-col gap-4">
                        <section
                            className={cn(cardClasses, 'grid gap-5 p-4 sm:p-5')}
                        >
                            <fieldset className="grid gap-2">
                                <legend className="mb-2 text-sm font-semibold text-ink-700">
                                    Financing type
                                </legend>
                                <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
                                    {types.map((option) => {
                                        const Icon = typeIcon(option);
                                        const isSelected =
                                            type === option.value;

                                        return (
                                            <label
                                                key={option.value}
                                                className={cn(
                                                    'flex cursor-pointer flex-col items-center gap-1.5 rounded-landing border px-2 py-3 text-center transition-colors has-focus-visible:ring-2 has-focus-visible:ring-highlight',
                                                    isSelected
                                                        ? 'border-brand bg-brand-faint/40 ring-2 ring-brand/15'
                                                        : 'border-surface-200 hover:border-brand/40',
                                                )}
                                            >
                                                <input
                                                    type="radio"
                                                    name="type"
                                                    value={option.value}
                                                    checked={isSelected}
                                                    onChange={() =>
                                                        setType(option.value)
                                                    }
                                                    className="sr-only"
                                                />
                                                <Icon className="size-5 text-brand" />
                                                <span className="text-xs leading-tight font-semibold text-ink">
                                                    {
                                                        option.label.split(
                                                            ' (',
                                                        )[0]
                                                    }
                                                </span>
                                            </label>
                                        );
                                    })}
                                </div>
                                {selectedType && (
                                    <p className="text-xs text-ink-500">
                                        {selectedType.description}
                                    </p>
                                )}
                            </fieldset>

                            <div className="grid gap-2">
                                <label
                                    htmlFor="amount"
                                    className="text-sm font-semibold text-ink-700"
                                >
                                    Amount needed
                                </label>
                                <NairaInput
                                    id="amount"
                                    value={amount}
                                    onChange={(event) =>
                                        setAmount(
                                            event.target.value.replace(
                                                /[^\d.]/g,
                                                '',
                                            ),
                                        )
                                    }
                                    aria-invalid={
                                        amountProblem ? true : undefined
                                    }
                                    className="h-11 rounded-landing text-[15px]"
                                />
                                <div className="flex flex-wrap gap-1.5">
                                    {quickAmounts.map((naira) => (
                                        <button
                                            key={naira}
                                            type="button"
                                            onClick={() =>
                                                setAmount(String(naira))
                                            }
                                            className={cn(
                                                'rounded-full border px-2.5 py-1 text-xs font-semibold transition-colors',
                                                amount === String(naira)
                                                    ? 'border-brand bg-brand text-white'
                                                    : 'border-surface-200 text-ink-500 hover:border-brand/40 hover:text-ink',
                                            )}
                                        >
                                            {formatNaira(naira * 100).replace(
                                                '.00',
                                                '',
                                            )}
                                        </button>
                                    ))}
                                </div>
                                {amountProblem && amount !== '' && (
                                    <p className="text-sm text-red-600">
                                        {amountProblem}
                                    </p>
                                )}
                            </div>

                            <fieldset className="grid gap-2">
                                <legend className="mb-2 text-sm font-semibold text-ink-700">
                                    Repay over
                                </legend>
                                <div className="grid grid-cols-3 gap-1.5 sm:grid-cols-6">
                                    {tenors.map((months) => (
                                        <button
                                            key={months}
                                            type="button"
                                            aria-pressed={tenor === months}
                                            onClick={() => setTenor(months)}
                                            className={cn(
                                                'rounded-landing border px-2 py-2 text-sm font-semibold transition-colors',
                                                tenor === months
                                                    ? 'border-brand bg-brand text-white'
                                                    : 'border-surface-200 text-ink-700 hover:border-brand/40',
                                            )}
                                        >
                                            {months}{' '}
                                            <span className="text-xs font-medium opacity-75">
                                                mo
                                            </span>
                                        </button>
                                    ))}
                                </div>
                            </fieldset>

                            <div className="grid gap-2">
                                <label
                                    htmlFor="income"
                                    className="text-sm font-semibold text-ink-700"
                                >
                                    Monthly income{' '}
                                    <span className="font-normal text-ink-400">
                                        (optional, checks affordability)
                                    </span>
                                </label>
                                <NairaInput
                                    id="income"
                                    value={income}
                                    placeholder="150000"
                                    onChange={(event) =>
                                        setIncome(
                                            event.target.value.replace(
                                                /[^\d.]/g,
                                                '',
                                            ),
                                        )
                                    }
                                    className="h-11 rounded-landing text-[15px]"
                                />
                            </div>
                        </section>

                        <section
                            aria-live="polite"
                            className="relative overflow-hidden rounded-landing-lg bg-linear-to-br from-brand to-brand-dark p-4 text-white shadow-landing sm:p-5"
                        >
                            <div
                                aria-hidden="true"
                                className="pointer-events-none absolute -top-24 -right-20 size-72 rounded-full bg-white/5"
                            />
                            <p className="relative text-sm text-white/75">
                                Estimated monthly repayment
                            </p>
                            <p className="relative mt-1 font-display text-3xl font-semibold tracking-[-0.02em] tabular-nums sm:text-4xl">
                                {monthly !== null ? formatNaira(monthly) : '—'}
                            </p>

                            <dl className="relative mt-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
                                {[
                                    [
                                        'Total to repay',
                                        amountKobo !== null &&
                                        amountProblem === null
                                            ? formatNaira(amountKobo)
                                            : '—',
                                    ],
                                    ['Duration', `${tenor} months`],
                                    [
                                        'First repayment',
                                        schedule[0]
                                            ? formatDate(schedule[0].dueDate)
                                            : '—',
                                    ],
                                    [
                                        'Last repayment',
                                        schedule.length
                                            ? formatDate(
                                                  schedule[schedule.length - 1]
                                                      .dueDate,
                                              )
                                            : '—',
                                    ],
                                ].map(([term, detail]) => (
                                    <div
                                        key={term}
                                        className="min-w-0 rounded-landing bg-white/8 px-3 py-2.5 ring-1 ring-white/10"
                                    >
                                        <dt className="text-xs text-white/60">
                                            {term}
                                        </dt>
                                        <dd className="mt-0.5 truncate text-sm font-semibold tabular-nums">
                                            {detail}
                                        </dd>
                                    </div>
                                ))}
                            </dl>

                            <div className="relative mt-4 rounded-landing bg-white/8 px-3 py-3 ring-1 ring-white/10">
                                <div className="flex items-center justify-between gap-3 text-xs">
                                    <span className="text-white/70">
                                        Share of monthly income
                                    </span>
                                    <span className="font-semibold">
                                        {share === null
                                            ? 'Add your income'
                                            : `${share}%`}
                                    </span>
                                </div>
                                <div className="mt-2 h-2 overflow-hidden rounded-full bg-white/15">
                                    <div
                                        className={cn(
                                            'h-full rounded-full transition-[width]',
                                            {
                                                good: 'bg-emerald-400',
                                                ok: 'bg-amber-300',
                                                high: 'bg-red-400',
                                                neutral: 'bg-white/30',
                                            }[shareTone],
                                        )}
                                        style={{
                                            width: `${Math.min(100, share ?? 0)}%`,
                                        }}
                                    />
                                </div>
                                <p className="mt-2 text-xs text-white/70">
                                    {
                                        {
                                            good: 'Comfortable — well within a third of your income.',
                                            ok: 'Manageable — close to our one-third guide.',
                                            high: 'High — try a longer term or a smaller amount.',
                                            neutral:
                                                'We look for repayments under a third of income.',
                                        }[shareTone]
                                    }
                                </p>
                            </div>
                        </section>

                        {schedule.length > 0 && (
                            <section className={cn(cardClasses, 'p-4 sm:p-5')}>
                                <div className="flex items-center justify-between gap-3">
                                    <h2 className="font-display text-base font-semibold text-ink">
                                        Repayment schedule
                                    </h2>
                                    <button
                                        type="button"
                                        onClick={() =>
                                            setShowTable((value) => !value)
                                        }
                                        aria-expanded={showTable}
                                        className="text-sm font-semibold text-brand hover:text-highlight-dark"
                                    >
                                        {showTable
                                            ? 'Hide table'
                                            : 'Show table'}
                                    </button>
                                </div>

                                <div
                                    role="img"
                                    aria-label={`${schedule.length} monthly repayments of about ${formatNaira(schedule[0].amount)}`}
                                    className="mt-4 flex h-28 items-end gap-1 sm:gap-1.5"
                                >
                                    {schedule.map((row) => (
                                        <div
                                            key={row.number}
                                            className="flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-1"
                                        >
                                            <div
                                                title={`Month ${row.number}: ${formatNaira(row.amount)}`}
                                                className="w-full max-w-8 rounded-t bg-highlight"
                                                style={{
                                                    height: `${Math.max(4, (row.amount / peak) * 100)}%`,
                                                }}
                                            />
                                            <span className="text-[10px] text-ink-400 tabular-nums">
                                                {row.number}
                                            </span>
                                        </div>
                                    ))}
                                </div>

                                {showTable && (
                                    <div className="mt-4 max-h-80 overflow-auto rounded-landing border border-surface-200">
                                        <table className="w-full text-sm">
                                            <thead className="sticky top-0 bg-surface-50 text-left text-xs text-ink-400">
                                                <tr>
                                                    <th className="px-3 py-2 font-medium">
                                                        #
                                                    </th>
                                                    <th className="px-3 py-2 font-medium">
                                                        Due
                                                    </th>
                                                    <th className="px-3 py-2 text-right font-medium">
                                                        Repayment
                                                    </th>
                                                    <th className="px-3 py-2 text-right font-medium">
                                                        Left after
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-surface-100">
                                                {schedule.map((row) => (
                                                    <tr key={row.number}>
                                                        <td className="px-3 py-2 text-ink-400">
                                                            {row.number}
                                                        </td>
                                                        <td className="px-3 py-2 text-ink-700">
                                                            {formatDate(
                                                                row.dueDate,
                                                            )}
                                                        </td>
                                                        <td className="px-3 py-2 text-right font-semibold text-ink tabular-nums">
                                                            {formatNaira(
                                                                row.amount,
                                                            )}
                                                        </td>
                                                        <td className="px-3 py-2 text-right text-ink-500 tabular-nums">
                                                            {formatNaira(
                                                                row.remaining,
                                                            )}
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                )}

                                <p className="mt-3 text-xs leading-relaxed text-ink-400">
                                    {repaidAsBorrowed
                                        ? `${selectedType?.label} is repaid at exactly the amount you borrow.`
                                        : 'Shown as the amount split evenly. The agreed price, rent or profit share is set at approval and shown to you before anything is paid out.'}{' '}
                                    Dates assume approval today.
                                </p>
                            </section>
                        )}

                        {canApply ? (
                            <Link
                                href={applyHref}
                                className="inline-flex h-11 items-center justify-center gap-2 rounded-full bg-brand px-5 text-[15px] font-semibold text-white transition-colors hover:bg-brand-hover"
                            >
                                Apply for this amount
                                <ArrowRight className="size-4" />
                            </Link>
                        ) : (
                            <p className="rounded-landing border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
                                {eligibility.hasOpenFinancing
                                    ? 'You already have financing open. You can apply again once it is closed.'
                                    : 'Verify your identity to apply for financing.'}
                            </p>
                        )}
                    </div>

                    <aside className="flex flex-col gap-4">
                        <section className="rounded-landing-lg border border-highlight/30 bg-highlight-faint p-4">
                            <h2 className="font-display text-base font-semibold text-ink">
                                No hidden charges, ever
                            </h2>
                            <p className="mt-1 text-sm leading-relaxed text-ink-700">
                                Our financing has no hidden charges. Any agreed
                                price or rent is fixed and shown before you
                                accept.
                            </p>
                        </section>

                        <section className={cn(cardClasses, 'p-4')}>
                            <h2 className="font-display text-base font-semibold text-ink">
                                Your eligibility
                            </h2>
                            <ul className="mt-3 grid gap-2.5">
                                {checklist.map((item) => (
                                    <li
                                        key={item.label}
                                        className="flex items-start gap-2.5 text-sm"
                                    >
                                        <span
                                            className={cn(
                                                'mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full',
                                                item.state === 'pass'
                                                    ? 'bg-highlight text-white'
                                                    : item.state === 'fail'
                                                      ? 'bg-red-100 text-red-700'
                                                      : 'bg-surface-100 text-ink-300',
                                            )}
                                        >
                                            {item.state === 'pass' ? (
                                                <Check className="size-3" />
                                            ) : item.state === 'fail' ? (
                                                <X className="size-3" />
                                            ) : (
                                                <CircleAlert className="size-3" />
                                            )}
                                        </span>
                                        <span className="min-w-0 flex-1 text-ink-700">
                                            {item.label}
                                            {item.hint && (
                                                <Link
                                                    href={item.hint.href}
                                                    className="ml-1.5 text-xs font-semibold text-brand hover:text-highlight-dark"
                                                >
                                                    {item.hint.text}
                                                </Link>
                                            )}
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        </section>

                        <section className={cn(cardClasses, 'p-4')}>
                            <h2 className="font-display text-base font-semibold text-ink">
                                Financing types
                            </h2>
                            <ul className="mt-3 grid gap-3">
                                {types.map((option) => {
                                    const Icon = typeIcon(option);

                                    return (
                                        <li key={option.value}>
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    setType(option.value)
                                                }
                                                className={cn(
                                                    'flex w-full items-start gap-3 rounded-landing p-1.5 text-left transition-colors hover:bg-surface-50',
                                                    type === option.value &&
                                                        'bg-surface-50',
                                                )}
                                            >
                                                <Icon className="mt-0.5 size-4 shrink-0 text-brand" />
                                                <span>
                                                    <span className="block text-sm font-semibold text-ink">
                                                        {option.label}
                                                    </span>
                                                    <span className="mt-0.5 block text-xs leading-relaxed text-ink-400">
                                                        {option.description}
                                                    </span>
                                                </span>
                                            </button>
                                        </li>
                                    );
                                })}
                            </ul>
                        </section>

                        <p className="flex items-start gap-2 px-1 text-xs text-ink-400">
                            <KeyRound className="mt-0.5 size-3.5 shrink-0" />
                            Repayments come from your wallet and are approved
                            with your transaction PIN.
                        </p>
                    </aside>
                </div>
            </MemberPage>
        </>
    );
}

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