import { Head, Link, useForm } from '@inertiajs/react';
import { ChevronDown, Plus, Trash2, UsersRound } from 'lucide-react';
import LoanController from '@/actions/App/Http/Controllers/LoanController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { formatNaira, formatRate } from '@/lib/format';
import { create, index } from '@/routes/loans';
import type { LoanProduct } from '@/types';

type Guarantor = {
    name: string;
    phone: string;
    address: string;
    occupation: string;
    relationship: string;
    member_id: string;
    id_number: string;
    photo: File | null;
    signature: File | null;
};

type Outsider = {
    name: string;
    phone: string;
    bvn: string;
    nin: string;
    photo: File | null;
};

const emptyOutsider: Outsider = {
    name: '',
    phone: '',
    bvn: '',
    nin: '',
    photo: null,
};

const emptyGuarantor: Guarantor = {
    name: '',
    phone: '',
    address: '',
    occupation: '',
    relationship: '',
    member_id: '',
    id_number: '',
    photo: null,
    signature: null,
};

const fieldClasses =
    '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';

const selectClasses =
    'h-10 w-full appearance-none rounded-md border border-input bg-white pr-9 pl-3 text-sm text-ink shadow-xs outline-none focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15';

/**
 * Same sums as LoanProduct::quote() on the server: flat monthly interest,
 * one-off processing and management fees, equal instalments. The server's figures are final.
 */
function quote(product: LoanProduct, principal: number, months: number) {
    const interest = Math.floor(
        (principal * product.interestRate * months + 5000) / 10000,
    );
    const total = principal + interest;

    return {
        interest,
        fee: Math.floor((principal * product.processingFee + 5000) / 10000),
        managementFee: Math.floor(
            (principal * product.managementFee + 5000) / 10000,
        ),
        total,
        monthly: Math.ceil(total / Math.max(1, months)),
    };
}

type ApplyingGroup = {
    id: number;
    name: string;
    accountNumber: string;
    members: { id: number; name: string; memberId: string }[];
};

export default function LoanApply({
    products,
    selectedProductId,
    group,
    newGroup,
}: {
    products: LoanProduct[];
    selectedProductId: number | null;
    group: ApplyingGroup | null;
    newGroup: boolean;
}) {
    const isGroupLoan = newGroup || group !== null;
    const heading = group
        ? `Group loan for ${group.name}`
        : newGroup
          ? 'Apply for a group loan'
          : 'Apply for a loan';

    const initial =
        products.find((product) => product.id === selectedProductId) ??
        products[0];

    const form = useForm({
        group_id: group ? String(group.id) : '',
        group_name: '',
        group_members: newGroup ? [''] : ([] as string[]),
        group_outsiders: [] as Outsider[],
        loan_product_id: initial ? String(initial.id) : '',
        amount: '',
        term_months: initial ? String(initial.minTermMonths) : '',
        purpose: '',
        monthly_income: '',
        existing_loans: '',
        guarantors: Array.from(
            { length: isGroupLoan ? 0 : (initial?.guarantorsRequired ?? 0) },
            () => ({ ...emptyGuarantor }),
        ),
        documents: [] as File[],
        terms: false,
    });
    const errors = form.errors as Record<string, string | undefined>;
    const product = products.find(
        (option) => String(option.id) === form.data.loan_product_id,
    );

    const chooseProduct = (id: string) => {
        const next = products.find((option) => String(option.id) === id);

        form.setData((data) => ({
            ...data,
            loan_product_id: id,
            term_months: next ? String(next.minTermMonths) : '',
            guarantors:
                !isGroupLoan &&
                next &&
                data.guarantors.length < next.guarantorsRequired
                    ? [
                          ...data.guarantors,
                          ...Array.from(
                              {
                                  length:
                                      next.guarantorsRequired -
                                      data.guarantors.length,
                              },
                              () => ({ ...emptyGuarantor }),
                          ),
                      ]
                    : data.guarantors,
        }));
    };

    const setGuarantor = (
        position: number,
        field: keyof Guarantor,
        value: string | File | null,
    ) =>
        form.setData(
            'guarantors',
            form.data.guarantors.map((guarantor, index) =>
                index === position
                    ? { ...guarantor, [field]: value }
                    : guarantor,
            ),
        );

    const principal = Math.round(Number(form.data.amount || 0) * 100);
    const months = Number(form.data.term_months || 0);
    const preview =
        product && principal > 0 && months > 0
            ? quote(product, principal, months)
            : null;

    const submit = (event: React.FormEvent) => {
        event.preventDefault();
        form.submit(LoanController.store());
    };

    if (!product) {
        return (
            <>
                <Head title={heading} />
                <MemberPage
                    title={heading}
                    description={
                        isGroupLoan
                            ? 'No group loans are on offer right now.'
                            : 'No loans are on offer right now.'
                    }
                >
                    <Link href={index()} className="text-sm text-brand">
                        Back to loans
                    </Link>
                </MemberPage>
            </>
        );
    }

    const terms = [
        `${product.interestRate > 0 ? `Interest is ${formatRate(product.interestRate)} of the amount borrowed for each month of the loan, and a` : 'A'} one-off processing fee of ${formatRate(product.processingFee)}${product.managementFee > 0 ? ` and management fee of ${formatRate(product.managementFee)}` : ''} is charged.`,
        `Repayments are due monthly. An instalment paid late attracts a penalty of ${formatRate(product.penaltyRate)} of the overdue amount each month${product.graceDays > 0 ? ` after ${product.graceDays} days` : ''}.`,
        isGroupLoan
            ? `As the group's leader you receive the loan and make the repayments. Every member of ${group?.name ?? 'the group'} is jointly responsible for repaying it in full.`
            : 'Your guarantors will be contacted to confirm they support your application.',
        'Information you give must be true and complete. The application is reviewed by a loan officer, a manager and the approval committee.',
    ];

    return (
        <>
            <Head title={heading} />

            <MemberPage
                title={heading}
                description="Fill in every section. You can follow your application from Loans."
            >
                <form onSubmit={submit} className="grid max-w-3xl gap-5">
                    <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 sm:grid-cols-2 sm:p-6">
                        <h2 className="font-display text-base font-semibold text-ink sm:col-span-2">
                            The loan
                        </h2>
                        <div className="grid content-start gap-2 sm:col-span-2">
                            <Label htmlFor="loan_product_id" required>
                                Loan type
                            </Label>
                            <div className="relative">
                                <select
                                    id="loan_product_id"
                                    value={form.data.loan_product_id}
                                    onChange={(event) =>
                                        chooseProduct(event.target.value)
                                    }
                                    className={selectClasses}
                                >
                                    {products.map((option) => (
                                        <option
                                            key={option.id}
                                            value={option.id}
                                        >
                                            {option.name} ·{' '}
                                            {option.categoryLabel}
                                        </option>
                                    ))}
                                </select>
                                <ChevronDown className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-ink-400" />
                            </div>
                            <p className="text-xs text-ink-400">
                                {formatNaira(product.minAmount)} –{' '}
                                {formatNaira(product.maxAmount)} over{' '}
                                {product.minTermMonths}–{product.maxTermMonths}{' '}
                                months · needs {product.minMembershipMonths}{' '}
                                months of membership
                                {product.minSavings > 0 &&
                                    ` and ${formatNaira(product.minSavings)} saved`}
                                {product.eligibilityNotes &&
                                    `. ${product.eligibilityNotes}`}
                            </p>
                            <InputError message={errors.loan_product_id} />
                        </div>
                        <div className="grid content-start gap-2">
                            <Label htmlFor="amount" required>
                                Amount
                            </Label>
                            <NairaInput
                                id="amount"
                                value={form.data.amount}
                                onChange={(event) =>
                                    form.setData(
                                        'amount',
                                        event.target.value.replace(
                                            /[^\d.]/g,
                                            '',
                                        ),
                                    )
                                }
                                placeholder={String(product.minAmount / 100)}
                            />
                            <InputError message={errors.amount} />
                        </div>
                        <div className="grid content-start gap-2">
                            <Label htmlFor="term_months" required>
                                Repayment period
                            </Label>
                            <div className="relative">
                                <select
                                    id="term_months"
                                    value={form.data.term_months}
                                    onChange={(event) =>
                                        form.setData(
                                            'term_months',
                                            event.target.value,
                                        )
                                    }
                                    className={selectClasses}
                                >
                                    {Array.from(
                                        {
                                            length:
                                                product.maxTermMonths -
                                                product.minTermMonths +
                                                1,
                                        },
                                        (_, offset) =>
                                            product.minTermMonths + offset,
                                    ).map((count) => (
                                        <option key={count} value={count}>
                                            {count}{' '}
                                            {count === 1 ? 'month' : 'months'}
                                        </option>
                                    ))}
                                </select>
                                <ChevronDown className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-ink-400" />
                            </div>
                            <InputError message={errors.term_months} />
                        </div>
                        {preview && (
                            <dl className="grid grid-cols-2 gap-3 rounded-landing bg-brand-faint/50 p-4 text-sm sm:col-span-2 sm:grid-cols-4">
                                <Preview
                                    term="Monthly"
                                    value={formatNaira(preview.monthly)}
                                />
                                {preview.interest > 0 && (
                                    <Preview
                                        term="Interest"
                                        value={formatNaira(preview.interest)}
                                    />
                                )}
                                <Preview
                                    term="Total to repay"
                                    value={formatNaira(preview.total)}
                                />
                                <Preview
                                    term="Processing fee"
                                    value={formatNaira(preview.fee)}
                                />
                                {preview.managementFee > 0 && (
                                    <Preview
                                        term="Management fee"
                                        value={formatNaira(
                                            preview.managementFee,
                                        )}
                                    />
                                )}
                            </dl>
                        )}
                        <div className="grid content-start gap-2 sm:col-span-2">
                            <Label htmlFor="purpose" required>
                                Purpose
                            </Label>
                            <textarea
                                id="purpose"
                                value={form.data.purpose}
                                onChange={(event) =>
                                    form.setData('purpose', event.target.value)
                                }
                                rows={3}
                                maxLength={2000}
                                placeholder="What will you use the money for?"
                                className={fieldClasses}
                            />
                            <InputError message={errors.purpose} />
                        </div>
                        <div className="grid content-start gap-2">
                            <Label htmlFor="monthly_income" required>
                                Monthly income
                            </Label>
                            <NairaInput
                                id="monthly_income"
                                value={form.data.monthly_income}
                                onChange={(event) =>
                                    form.setData(
                                        'monthly_income',
                                        event.target.value.replace(
                                            /[^\d.]/g,
                                            '',
                                        ),
                                    )
                                }
                            />
                            <InputError message={errors.monthly_income} />
                        </div>
                        <div className="grid content-start gap-2">
                            <Label htmlFor="existing_loans">
                                Existing loans
                            </Label>
                            <Input
                                id="existing_loans"
                                value={form.data.existing_loans}
                                onChange={(event) =>
                                    form.setData(
                                        'existing_loans',
                                        event.target.value,
                                    )
                                }
                                maxLength={1000}
                                placeholder="Leave empty if none, e.g. ₦50,000 with a bank, ₦8,000 a month"
                            />
                            <InputError message={errors.existing_loans} />
                        </div>
                    </section>

                    {newGroup && (
                        <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                            <div>
                                <h2 className="font-display text-base font-semibold text-ink">
                                    Your group
                                </h2>
                                <p className="text-xs text-ink-400">
                                    You become the group's leader. Add the
                                    membership ID of everyone on Smart Save, and
                                    the details of anyone who isn't. No
                                    guarantors are needed: every member is
                                    jointly responsible for this loan.
                                </p>
                            </div>
                            <div className="grid content-start gap-2">
                                <Label htmlFor="group_name" required>
                                    Group name
                                </Label>
                                <Input
                                    id="group_name"
                                    value={form.data.group_name}
                                    onChange={(event) =>
                                        form.setData(
                                            'group_name',
                                            event.target.value,
                                        )
                                    }
                                    maxLength={80}
                                    placeholder="e.g. Pantami Women Traders"
                                />
                                <InputError message={errors.group_name} />
                            </div>
                            <div className="grid content-start gap-2">
                                <Label>Members on Smart Save</Label>
                                <InputError message={errors.group_members} />
                                {form.data.group_members.map(
                                    (memberId, position) => (
                                        <div
                                            key={position}
                                            className="grid gap-1"
                                        >
                                            <div className="flex items-center gap-2">
                                                <Input
                                                    value={memberId}
                                                    onChange={(event) =>
                                                        form.setData(
                                                            'group_members',
                                                            form.data.group_members.map(
                                                                (
                                                                    value,
                                                                    index,
                                                                ) =>
                                                                    index ===
                                                                    position
                                                                        ? event
                                                                              .target
                                                                              .value
                                                                        : value,
                                                            ),
                                                        )
                                                    }
                                                    maxLength={20}
                                                    placeholder="Membership ID, e.g. ADS-000123"
                                                    aria-label={`Member ${position + 1} membership ID`}
                                                />
                                                {form.data.group_members
                                                    .length > 1 && (
                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            form.setData(
                                                                'group_members',
                                                                form.data.group_members.filter(
                                                                    (
                                                                        _,
                                                                        index,
                                                                    ) =>
                                                                        index !==
                                                                        position,
                                                                ),
                                                            )
                                                        }
                                                        className="rounded-full p-1.5 text-ink-400 hover:bg-surface-100 hover:text-red-600"
                                                        aria-label={`Remove member ${position + 1}`}
                                                    >
                                                        <Trash2 className="size-4" />
                                                    </button>
                                                )}
                                            </div>
                                            <InputError
                                                message={
                                                    errors[
                                                        `group_members.${position}`
                                                    ]
                                                }
                                            />
                                        </div>
                                    ),
                                )}
                                {form.data.group_members.length < 30 && (
                                    <button
                                        type="button"
                                        onClick={() =>
                                            form.setData('group_members', [
                                                ...form.data.group_members,
                                                '',
                                            ])
                                        }
                                        className="inline-flex w-fit items-center gap-1 text-sm font-semibold text-brand hover:text-brand-hover"
                                    >
                                        <Plus className="size-4" />
                                        Add a member
                                    </button>
                                )}
                            </div>
                            <div className="grid content-start gap-3">
                                <div>
                                    <Label>People not on Smart Save</Label>
                                    <p className="text-xs text-ink-400">
                                        For anyone without a Smart Save account,
                                        give their BVN, NIN and a clear photo of
                                        their face.
                                    </p>
                                </div>
                                {form.data.group_outsiders.map(
                                    (outsider, position) => {
                                        const field = (
                                            key: keyof Outsider,
                                            value: string | File | null,
                                        ) =>
                                            form.setData(
                                                'group_outsiders',
                                                form.data.group_outsiders.map(
                                                    (item, index) =>
                                                        index === position
                                                            ? {
                                                                  ...item,
                                                                  [key]: value,
                                                              }
                                                            : item,
                                                ),
                                            );
                                        const error = (key: string) =>
                                            errors[
                                                `group_outsiders.${position}.${key}`
                                            ];

                                        return (
                                            <fieldset
                                                key={position}
                                                className="grid gap-3 rounded-landing border border-surface-200 p-4 sm:grid-cols-2"
                                            >
                                                <legend className="flex w-full items-center justify-between px-1 text-sm font-semibold text-ink">
                                                    Person {position + 1}
                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            form.setData(
                                                                'group_outsiders',
                                                                form.data.group_outsiders.filter(
                                                                    (
                                                                        _,
                                                                        index,
                                                                    ) =>
                                                                        index !==
                                                                        position,
                                                                ),
                                                            )
                                                        }
                                                        className="rounded-full p-1 text-ink-400 hover:bg-surface-100 hover:text-red-600"
                                                        aria-label={`Remove person ${position + 1}`}
                                                    >
                                                        <Trash2 className="size-4" />
                                                    </button>
                                                </legend>
                                                <div className="grid content-start gap-1.5">
                                                    <Label
                                                        htmlFor={`outsider-${position}-name`}
                                                        required
                                                    >
                                                        Full name
                                                    </Label>
                                                    <Input
                                                        id={`outsider-${position}-name`}
                                                        value={outsider.name}
                                                        onChange={(event) =>
                                                            field(
                                                                'name',
                                                                event.target
                                                                    .value,
                                                            )
                                                        }
                                                        maxLength={120}
                                                    />
                                                    <InputError
                                                        message={error('name')}
                                                    />
                                                </div>
                                                <div className="grid content-start gap-1.5">
                                                    <Label
                                                        htmlFor={`outsider-${position}-phone`}
                                                        required
                                                    >
                                                        Phone
                                                    </Label>
                                                    <Input
                                                        id={`outsider-${position}-phone`}
                                                        type="tel"
                                                        value={outsider.phone}
                                                        onChange={(event) =>
                                                            field(
                                                                'phone',
                                                                event.target
                                                                    .value,
                                                            )
                                                        }
                                                        placeholder="08012345678"
                                                        maxLength={20}
                                                    />
                                                    <InputError
                                                        message={error('phone')}
                                                    />
                                                </div>
                                                <div className="grid content-start gap-1.5">
                                                    <Label
                                                        htmlFor={`outsider-${position}-bvn`}
                                                        required
                                                    >
                                                        BVN
                                                    </Label>
                                                    <Input
                                                        id={`outsider-${position}-bvn`}
                                                        inputMode="numeric"
                                                        value={outsider.bvn}
                                                        onChange={(event) =>
                                                            field(
                                                                'bvn',
                                                                event.target.value
                                                                    .replace(
                                                                        /\D/g,
                                                                        '',
                                                                    )
                                                                    .slice(
                                                                        0,
                                                                        11,
                                                                    ),
                                                            )
                                                        }
                                                        placeholder="11 digits"
                                                    />
                                                    <InputError
                                                        message={error('bvn')}
                                                    />
                                                </div>
                                                <div className="grid content-start gap-1.5">
                                                    <Label
                                                        htmlFor={`outsider-${position}-nin`}
                                                        required
                                                    >
                                                        NIN
                                                    </Label>
                                                    <Input
                                                        id={`outsider-${position}-nin`}
                                                        inputMode="numeric"
                                                        value={outsider.nin}
                                                        onChange={(event) =>
                                                            field(
                                                                'nin',
                                                                event.target.value
                                                                    .replace(
                                                                        /\D/g,
                                                                        '',
                                                                    )
                                                                    .slice(
                                                                        0,
                                                                        11,
                                                                    ),
                                                            )
                                                        }
                                                        placeholder="11 digits"
                                                    />
                                                    <InputError
                                                        message={error('nin')}
                                                    />
                                                </div>
                                                <div className="grid content-start gap-1.5 sm:col-span-2">
                                                    <Label
                                                        htmlFor={`outsider-${position}-photo`}
                                                        required
                                                    >
                                                        Photo
                                                    </Label>
                                                    <input
                                                        id={`outsider-${position}-photo`}
                                                        type="file"
                                                        accept="image/jpeg,image/png"
                                                        onChange={(event) =>
                                                            field(
                                                                'photo',
                                                                event.target
                                                                    .files?.[0] ??
                                                                    null,
                                                            )
                                                        }
                                                        className="block w-full text-xs text-ink-500 file:mr-2 file:rounded-full file:border-0 file:bg-brand-faint file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-brand"
                                                    />
                                                    <p className="text-xs text-ink-400">
                                                        JPG or PNG, face clearly
                                                        visible, up to 2 MB.
                                                    </p>
                                                    <InputError
                                                        message={error('photo')}
                                                    />
                                                </div>
                                            </fieldset>
                                        );
                                    },
                                )}
                                {form.data.group_members.length +
                                    form.data.group_outsiders.length <
                                    30 && (
                                    <button
                                        type="button"
                                        onClick={() =>
                                            form.setData('group_outsiders', [
                                                ...form.data.group_outsiders,
                                                { ...emptyOutsider },
                                            ])
                                        }
                                        className="inline-flex w-fit items-center gap-1 text-sm font-semibold text-brand hover:text-brand-hover"
                                    >
                                        <Plus className="size-4" />
                                        Add someone not on Smart Save
                                    </button>
                                )}
                            </div>
                        </section>
                    )}

                    {newGroup ? null : group ? (
                        <section className="grid gap-3 rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                            <div>
                                <h2 className="font-display text-base font-semibold text-ink">
                                    Group members
                                </h2>
                                <p className="text-xs text-ink-400">
                                    No guarantors are needed. These members of{' '}
                                    {group.name} ({group.accountNumber}) are
                                    jointly responsible for this loan.
                                </p>
                                <InputError message={errors.group_id} />
                            </div>
                            <ul className="grid gap-2 sm:grid-cols-2">
                                {group.members.map((member) => (
                                    <li
                                        key={member.id}
                                        className="flex items-center gap-2 rounded-landing border border-surface-100 bg-surface-50 px-3 py-2 text-sm"
                                    >
                                        <UsersRound className="size-4 shrink-0 text-brand" />
                                        <span className="min-w-0 flex-1 truncate font-medium text-ink">
                                            {member.name}
                                        </span>
                                        <span className="font-mono text-xs text-ink-400">
                                            {member.memberId}
                                        </span>
                                    </li>
                                ))}
                            </ul>
                        </section>
                    ) : (
                        <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                            <div>
                                <h2 className="font-display text-base font-semibold text-ink">
                                    Guarantors
                                </h2>
                                <p className="text-xs text-ink-400">
                                    {product.guarantorsRequired > 0
                                        ? `This loan needs ${product.guarantorsRequired} guarantor${product.guarantorsRequired === 1 ? '' : 's'}.`
                                        : 'This loan does not need a guarantor, but you may add one.'}{' '}
                                    If a guarantor is a member, add their
                                    membership ID.
                                </p>
                                <InputError message={errors.guarantors} />
                            </div>
                            {form.data.guarantors.map((guarantor, position) => (
                                <fieldset
                                    key={position}
                                    className="grid gap-3 rounded-landing border border-surface-200 p-4 sm:grid-cols-2"
                                >
                                    <legend className="flex w-full items-center justify-between px-1 text-sm font-semibold text-ink-700">
                                        Guarantor {position + 1}
                                    </legend>
                                    {(
                                        [
                                            ['name', 'Full name', true],
                                            ['phone', 'Phone', true],
                                            ['occupation', 'Occupation', true],
                                            [
                                                'relationship',
                                                'Relationship',
                                                true,
                                            ],
                                            ['address', 'Address', true],
                                            [
                                                'id_number',
                                                'ID number (NIN, voter’s card…)',
                                                true,
                                            ],
                                            [
                                                'member_id',
                                                'Membership ID (if a member)',
                                                false,
                                            ],
                                        ] as const
                                    ).map(([field, label, required]) => (
                                        <div
                                            key={field}
                                            className="grid content-start gap-1.5"
                                        >
                                            <Label
                                                htmlFor={`guarantor-${position}-${field}`}
                                                required={required}
                                            >
                                                {label}
                                            </Label>
                                            <Input
                                                id={`guarantor-${position}-${field}`}
                                                value={guarantor[field] ?? ''}
                                                onChange={(event) =>
                                                    setGuarantor(
                                                        position,
                                                        field,
                                                        event.target.value,
                                                    )
                                                }
                                                placeholder={
                                                    field === 'member_id'
                                                        ? 'ADS-000125'
                                                        : field === 'phone'
                                                          ? '08012345678'
                                                          : undefined
                                                }
                                            />
                                            <InputError
                                                message={
                                                    errors[
                                                        `guarantors.${position}.${field}`
                                                    ]
                                                }
                                            />
                                        </div>
                                    ))}
                                    {(['photo', 'signature'] as const).map(
                                        (field) => (
                                            <div
                                                key={field}
                                                className="grid content-start gap-1.5"
                                            >
                                                <Label
                                                    htmlFor={`guarantor-${position}-${field}`}
                                                >
                                                    {field === 'photo'
                                                        ? 'Passport photo'
                                                        : 'Signature'}
                                                </Label>
                                                <input
                                                    id={`guarantor-${position}-${field}`}
                                                    type="file"
                                                    accept="image/jpeg,image/png"
                                                    onChange={(event) =>
                                                        setGuarantor(
                                                            position,
                                                            field,
                                                            event.target
                                                                .files?.[0] ??
                                                                null,
                                                        )
                                                    }
                                                    className="block w-full text-xs text-ink-500 file:mr-2 file:rounded-full file:border-0 file:bg-brand-faint file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-brand"
                                                />
                                                <InputError
                                                    message={
                                                        errors[
                                                            `guarantors.${position}.${field}`
                                                        ]
                                                    }
                                                />
                                            </div>
                                        ),
                                    )}
                                    <p className="text-xs text-ink-400 sm:col-span-2">
                                        Photo and signature are optional now;
                                        the guarantor can also bring them to the
                                        office.
                                    </p>
                                    {form.data.guarantors.length >
                                        product.guarantorsRequired && (
                                        <button
                                            type="button"
                                            onClick={() =>
                                                form.setData(
                                                    'guarantors',
                                                    form.data.guarantors.filter(
                                                        (_, index) =>
                                                            index !== position,
                                                    ),
                                                )
                                            }
                                            className="inline-flex w-fit items-center gap-1 text-sm font-semibold text-red-600 hover:text-red-700 sm:col-span-2"
                                        >
                                            <Trash2 className="size-4" />
                                            Remove
                                        </button>
                                    )}
                                </fieldset>
                            ))}
                            {form.data.guarantors.length < 5 && (
                                <button
                                    type="button"
                                    onClick={() =>
                                        form.setData('guarantors', [
                                            ...form.data.guarantors,
                                            { ...emptyGuarantor },
                                        ])
                                    }
                                    className="inline-flex w-fit items-center gap-1 text-sm font-semibold text-brand hover:text-brand-hover"
                                >
                                    <Plus className="size-4" />
                                    Add a guarantor
                                </button>
                            )}
                        </section>
                    )}

                    <section className="grid gap-3 rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                        <div>
                            <Label htmlFor="documents">
                                Supporting documents
                            </Label>
                            <p className="text-xs text-ink-400">
                                Up to 5 files (PDF, JPG or PNG, 5 MB each), such
                                as a bank statement, pay slip, business papers
                                or school fees invoice.
                            </p>
                        </div>
                        <input
                            id="documents"
                            type="file"
                            multiple
                            accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png"
                            onChange={(event) =>
                                form.setData(
                                    'documents',
                                    Array.from(event.target.files ?? []).slice(
                                        0,
                                        5,
                                    ),
                                )
                            }
                            className="block w-full text-sm text-ink-500 file:mr-3 file:rounded-full file:border-0 file:bg-brand-faint file:px-4 file:py-2 file:text-sm file:font-semibold file:text-brand"
                        />
                        {form.progress && (
                            <progress
                                value={form.progress.percentage}
                                max="100"
                                className="h-1.5 w-full"
                            >
                                {form.progress.percentage}%
                            </progress>
                        )}
                        <InputError message={errors.documents} />
                        {form.data.documents.map((_, position) => (
                            <InputError
                                key={position}
                                message={errors[`documents.${position}`]}
                            />
                        ))}
                    </section>

                    <section className="grid gap-3 rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                        <h2 className="font-display text-base font-semibold text-ink">
                            Loan terms
                        </h2>
                        <ul className="list-disc space-y-1 pl-5 text-sm text-ink-700">
                            {terms.map((term) => (
                                <li key={term}>{term}</li>
                            ))}
                        </ul>
                        <label className="flex items-center gap-2 text-sm text-ink-700">
                            <Checkbox
                                checked={form.data.terms}
                                onCheckedChange={(state) =>
                                    form.setData('terms', state === true)
                                }
                            />
                            I have read and accept these terms
                        </label>
                        <InputError message={errors.terms} />
                    </section>

                    <div className="flex items-center gap-2">
                        <Button disabled={form.processing}>
                            Submit application
                        </Button>
                        <Link
                            href={index()}
                            className="rounded-full px-3.5 py-1.5 text-sm font-semibold text-ink-500 hover:text-ink"
                        >
                            Cancel
                        </Link>
                    </div>
                </form>
            </MemberPage>
        </>
    );
}

function Preview({ term, value }: { term: string; value: string }) {
    return (
        <div className="min-w-0">
            <dt className="text-xs text-ink-500">{term}</dt>
            <dd className="truncate font-semibold text-ink tabular-nums">
                {value}
            </dd>
        </div>
    );
}

LoanApply.layout = {
    breadcrumbs: [
        { title: 'Loans', href: index() },
        { title: 'Apply', href: create() },
    ],
};
