import { Form, Head, usePage } from '@inertiajs/react';
import { useState } from 'react';
import FinancingController from '@/actions/App/Http/Controllers/FinancingController';
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 { cn } from '@/lib/utils';
import { create, index } from '@/routes/financing';
import type { FinancingTypeOption } from '@/types';

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

const terms = [
    'Financing is transparent. Any price, rent or profit share is agreed and shown to you before payout; types without one are repaid at exactly the amount borrowed.',
    'Repayments are due monthly from your wallet on the dates in your schedule.',
    'Your guarantor may be contacted to confirm they support your application.',
    'We review your bank statement and repayment history to make a decision. Information you give must be true and complete.',
    'Late repayments are never charged interest. We will contact you to agree a plan if you fall behind.',
];

export default function FinancingApply({
    types,
    tenors,
}: {
    types: FinancingTypeOption[];
    tenors: number[];
}) {
    // Values carried over from the financing calculator, if any.
    const query = new URLSearchParams(usePage().url.split('?')[1] ?? '');
    const isNaira = (value: string | null): value is string =>
        value !== null && /^\d{1,10}(\.\d{1,2})?$/.test(value);
    const presetType = types.some((type) => type.value === query.get('type'))
        ? (query.get('type') as string)
        : null;
    const presetTenor = tenors.includes(Number(query.get('tenor')))
        ? Number(query.get('tenor'))
        : tenors[1];
    const presetAmount = isNaira(query.get('amount'))
        ? (query.get('amount') as string)
        : undefined;
    const presetIncome = isNaira(query.get('income'))
        ? (query.get('income') as string)
        : undefined;

    const [selectedType, setSelectedType] = useState(
        presetType ?? types[0]?.value ?? '',
    );

    return (
        <>
            <Head title="Apply for financing" />

            <MemberPage
                title="Apply for financing"
                description="Most applications get a decision within 3 working days."
            >
                <Form
                    {...FinancingController.store.form()}
                    className="grid max-w-3xl gap-6"
                >
                    {({ processing, errors, progress }) => (
                        <>
                            <fieldset className="grid gap-3">
                                <legend className="mb-3 text-sm font-semibold text-ink-700">
                                    Type of financing
                                </legend>
                                <div className="grid gap-3 sm:grid-cols-2">
                                    {types.map((type) => (
                                        <label
                                            key={type.value}
                                            className={cn(
                                                'flex cursor-pointer gap-3 rounded-landing-lg border bg-white p-4',
                                                selectedType === type.value
                                                    ? 'border-brand ring-2 ring-brand/15'
                                                    : 'border-surface-200 hover:border-brand-border',
                                            )}
                                        >
                                            <input
                                                type="radio"
                                                name="type"
                                                value={type.value}
                                                checked={
                                                    selectedType === type.value
                                                }
                                                onChange={() =>
                                                    setSelectedType(type.value)
                                                }
                                                className="mt-1 accent-brand"
                                            />
                                            <span>
                                                <span className="block text-sm font-semibold text-ink">
                                                    {type.label}
                                                </span>
                                                <span className="mt-0.5 block text-xs text-ink-500">
                                                    {type.description}
                                                </span>
                                            </span>
                                        </label>
                                    ))}
                                </div>
                                <InputError message={errors.type} />
                            </fieldset>

                            <div className="grid gap-5 rounded-landing-lg border border-surface-200 bg-white p-5 sm:grid-cols-2 sm:p-6">
                                <div className="grid gap-2">
                                    <Label htmlFor="amount_requested" required>
                                        Amount needed
                                    </Label>
                                    <NairaInput
                                        id="amount_requested"
                                        name="amount_requested"
                                        required
                                        defaultValue={presetAmount}
                                        placeholder="300000"
                                    />
                                    <InputError
                                        message={errors.amount_requested}
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="tenor_months">
                                        Repay over
                                    </Label>
                                    <select
                                        id="tenor_months"
                                        name="tenor_months"
                                        defaultValue={presetTenor}
                                        className={selectClasses}
                                    >
                                        {tenors.map((months) => (
                                            <option key={months} value={months}>
                                                {months} months
                                            </option>
                                        ))}
                                    </select>
                                    <InputError message={errors.tenor_months} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="monthly_income" required>
                                        Monthly income
                                    </Label>
                                    <NairaInput
                                        id="monthly_income"
                                        name="monthly_income"
                                        required
                                        defaultValue={presetIncome}
                                        placeholder="150000"
                                    />
                                    <InputError
                                        message={errors.monthly_income}
                                    />
                                </div>
                                <div className="hidden sm:block" />
                                <div className="grid gap-2 sm:col-span-2">
                                    <Label htmlFor="purpose" required>
                                        What is it for?
                                    </Label>
                                    <textarea
                                        id="purpose"
                                        name="purpose"
                                        required
                                        rows={4}
                                        maxLength={2000}
                                        placeholder="Describe the item or business need, and how it will help you repay."
                                        className="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"
                                    />
                                    <InputError message={errors.purpose} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="guarantor_name" required>
                                        Guarantor's full name
                                    </Label>
                                    <Input
                                        id="guarantor_name"
                                        name="guarantor_name"
                                        required
                                        maxLength={120}
                                    />
                                    <InputError
                                        message={errors.guarantor_name}
                                    />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="guarantor_phone" required>
                                        Guarantor's phone
                                    </Label>
                                    <Input
                                        id="guarantor_phone"
                                        name="guarantor_phone"
                                        type="tel"
                                        required
                                        placeholder="08012345678"
                                    />
                                    <InputError
                                        message={errors.guarantor_phone}
                                    />
                                </div>
                                <div className="grid gap-2 sm:col-span-2">
                                    <Label htmlFor="statement" required>
                                        Bank statement (last 6 months, PDF)
                                    </Label>
                                    <input
                                        id="statement"
                                        name="statement"
                                        type="file"
                                        required
                                        accept=".pdf,application/pdf"
                                        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"
                                    />
                                    {progress && (
                                        <progress
                                            value={progress.percentage}
                                            max="100"
                                            className="h-1.5 w-full"
                                        >
                                            {progress.percentage}%
                                        </progress>
                                    )}
                                    <InputError message={errors.statement} />
                                </div>
                            </div>

                            <section className="rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                                <h2 className="font-semibold text-ink">
                                    Financing terms
                                </h2>
                                <ul className="mt-3 list-disc space-y-1.5 pl-5 text-sm text-ink-500">
                                    {terms.map((term) => (
                                        <li key={term}>{term}</li>
                                    ))}
                                </ul>
                                <div className="mt-4 flex items-start gap-3">
                                    <Checkbox
                                        id="terms"
                                        name="terms"
                                        value="1"
                                        required
                                        className="mt-0.5"
                                    />
                                    <Label
                                        htmlFor="terms"
                                        required
                                        className="leading-snug font-normal text-ink-700"
                                    >
                                        I have read and accept these terms, and
                                        the information I have given is true.
                                    </Label>
                                </div>
                                <InputError
                                    message={errors.terms}
                                    className="mt-2"
                                />
                            </section>

                            <div>
                                <Button disabled={processing}>
                                    Submit application
                                </Button>
                            </div>
                        </>
                    )}
                </Form>
            </MemberPage>
        </>
    );
}

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