import { Head, Link, useForm } from '@inertiajs/react';
import { ChevronDown } from 'lucide-react';
import LoanProductController from '@/actions/App/Http/Controllers/Admin/LoanProductController';
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 { index } from '@/routes/admin/loan-products';
import type { LoanProduct, SelectOption } from '@/types';

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 naira = (kobo: number) => String(kobo / 100);
const percent = (basisPoints: number) => String(basisPoints / 100);
const decimal = (value: string) => value.replace(/[^\d.]/g, '');
const whole = (value: string) => value.replace(/\D/g, '');

export default function LoanProductForm({
    product,
    categories,
}: {
    product: LoanProduct | null;
    categories: SelectOption[];
}) {
    const form = useForm({
        name: product?.name ?? '',
        category: product?.category ?? categories[0]?.value ?? '',
        description: product?.description ?? '',
        min_amount: product ? naira(product.minAmount) : '',
        max_amount: product ? naira(product.maxAmount) : '',
        // Not shown on the form: new products charge no interest, and an
        // existing product keeps the rate it already has.
        interest_rate: product ? percent(product.interestRate) : '0',
        processing_fee: product ? percent(product.processingFee) : '0',
        management_fee: product ? percent(product.managementFee) : '0',
        min_term_months: product ? String(product.minTermMonths) : '1',
        max_term_months: product ? String(product.maxTermMonths) : '12',
        penalty_rate: product ? percent(product.penaltyRate) : '0',
        grace_days: product ? String(product.graceDays) : '0',
        min_membership_months: product
            ? String(product.minMembershipMonths)
            : '0',
        min_savings:
            product && product.minSavings > 0 ? naira(product.minSavings) : '',
        guarantors_required: product ? String(product.guarantorsRequired) : '0',
        eligibility_notes: product?.eligibilityNotes ?? '',
        for_groups: product?.forGroups ?? false,
        is_active: product?.isActive ?? true,
    });

    type Field = keyof typeof form.data;

    const submit = (event: React.FormEvent) => {
        event.preventDefault();

        if (product) {
            form.submit(LoanProductController.update(product.id));
        } else {
            form.submit(LoanProductController.store());
        }
    };

    const numberField = (
        field: Field,
        label: string,
        suffix: string,
        clean: (value: string) => string,
        required = true,
    ) => (
        <div className="grid content-start gap-2">
            <Label htmlFor={field} required={required}>
                {label}
            </Label>
            <div className="relative">
                <Input
                    id={field}
                    inputMode="decimal"
                    value={String(form.data[field])}
                    onChange={(event) =>
                        form.setData(field, clean(event.target.value))
                    }
                    className="pr-20"
                />
                <span className="pointer-events-none absolute top-1/2 right-3 -translate-y-1/2 text-xs text-ink-400">
                    {suffix}
                </span>
            </div>
            <InputError message={form.errors[field]} />
        </div>
    );

    const nairaField = (field: Field, label: string, required = true) => (
        <div className="grid content-start gap-2">
            <Label htmlFor={field} required={required}>
                {label}
            </Label>
            <NairaInput
                id={field}
                value={String(form.data[field])}
                onChange={(event) =>
                    form.setData(field, decimal(event.target.value))
                }
            />
            <InputError message={form.errors[field]} />
        </div>
    );

    const title = product ? `Edit ${product.name}` : 'New loan product';

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

            <MemberPage
                title={title}
                description="Limits, pricing and eligibility for one type of loan."
            >
                <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">
                        <div className="grid content-start gap-2">
                            <Label htmlFor="name" required>
                                Product name
                            </Label>
                            <Input
                                id="name"
                                value={form.data.name}
                                onChange={(event) =>
                                    form.setData('name', event.target.value)
                                }
                                maxLength={80}
                                placeholder="e.g. Business Booster"
                            />
                            <InputError message={form.errors.name} />
                        </div>
                        <div className="grid content-start gap-2">
                            <Label htmlFor="category" required>
                                Loan type
                            </Label>
                            <div className="relative">
                                <select
                                    id="category"
                                    value={form.data.category}
                                    onChange={(event) =>
                                        form.setData(
                                            'category',
                                            event.target.value,
                                        )
                                    }
                                    className="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"
                                >
                                    {categories.map((category) => (
                                        <option
                                            key={category.value}
                                            value={category.value}
                                        >
                                            {category.label}
                                        </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={form.errors.category} />
                        </div>
                        <div className="grid content-start gap-2 sm:col-span-2">
                            <Label htmlFor="description">Description</Label>
                            <textarea
                                id="description"
                                value={form.data.description}
                                onChange={(event) =>
                                    form.setData(
                                        'description',
                                        event.target.value,
                                    )
                                }
                                rows={2}
                                maxLength={1000}
                                placeholder="Who the loan is for and what it can be used for"
                                className={fieldClasses}
                            />
                            <InputError message={form.errors.description} />
                        </div>
                    </section>

                    <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">
                            Amount and term
                        </h2>
                        {nairaField('min_amount', 'Smallest loan')}
                        {nairaField('max_amount', 'Largest loan')}
                        {numberField(
                            'min_term_months',
                            'Shortest term',
                            'months',
                            whole,
                        )}
                        {numberField(
                            'max_term_months',
                            'Longest term',
                            'months',
                            whole,
                        )}
                    </section>

                    <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 sm:grid-cols-2 sm:p-6">
                        <div className="sm:col-span-2">
                            <h2 className="font-display text-base font-semibold text-ink">
                                Fees and penalty
                            </h2>
                        </div>
                        {numberField(
                            'processing_fee',
                            'Processing fee',
                            '% once',
                            decimal,
                        )}
                        {numberField(
                            'management_fee',
                            'Management fee',
                            '% once',
                            decimal,
                        )}
                        {numberField(
                            'penalty_rate',
                            'Late penalty',
                            '% of overdue',
                            decimal,
                        )}
                        {numberField(
                            'grace_days',
                            'Grace period',
                            'days',
                            whole,
                        )}
                    </section>

                    <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 sm:grid-cols-3 sm:p-6">
                        <h2 className="font-display text-base font-semibold text-ink sm:col-span-3">
                            Eligibility
                        </h2>
                        {numberField(
                            'min_membership_months',
                            'Membership',
                            'months',
                            whole,
                        )}
                        {nairaField('min_savings', 'Minimum savings', false)}
                        {numberField(
                            'guarantors_required',
                            'Guarantors',
                            'people',
                            whole,
                        )}
                        <div className="grid content-start gap-2 sm:col-span-3">
                            <Label htmlFor="eligibility_notes">
                                Other requirements
                            </Label>
                            <textarea
                                id="eligibility_notes"
                                value={form.data.eligibility_notes}
                                onChange={(event) =>
                                    form.setData(
                                        'eligibility_notes',
                                        event.target.value,
                                    )
                                }
                                rows={3}
                                maxLength={3000}
                                placeholder="e.g. A registered business, or a letter from the employer for salary loans."
                                className={fieldClasses}
                            />
                            <InputError
                                message={form.errors.eligibility_notes}
                            />
                        </div>
                        <label className="flex items-center gap-2 text-sm text-ink-700 sm:col-span-3">
                            <Checkbox
                                checked={form.data.is_active}
                                onCheckedChange={(state) =>
                                    form.setData('is_active', state === true)
                                }
                            />
                            Members can apply for this product
                        </label>
                        <label className="flex items-start gap-2 text-sm text-ink-700 sm:col-span-3">
                            <Checkbox
                                checked={form.data.for_groups}
                                onCheckedChange={(state) =>
                                    form.setData('for_groups', state === true)
                                }
                                className="mt-0.5"
                            />
                            <span>
                                Group loan
                                <span className="block text-xs text-ink-400">
                                    Only Smart Save group leaders can apply, on
                                    the group's behalf. The loan is paid to the
                                    leader, the group's members are jointly
                                    responsible and no guarantors are needed.
                                    Members can't use this product for their own
                                    loans.
                                </span>
                            </span>
                        </label>
                    </section>

                    <div className="flex items-center gap-2">
                        <Button disabled={form.processing}>
                            {product ? 'Save changes' : 'Create product'}
                        </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>
        </>
    );
}

LoanProductForm.layout = {
    breadcrumbs: [{ title: 'Loan products', href: index() }],
};
