import { Head, Link, useForm } from '@inertiajs/react';
import { Banknote, Landmark, ShieldCheck } from 'lucide-react';
import WithdrawalController from '@/actions/App/Http/Controllers/WithdrawalController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import { PinField, toKobo } from '@/components/member/transfer-parts';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { create, index } from '@/routes/withdrawals';
import type { SelectOption } from '@/types';

export default function WithdrawalsCreate({
    balance,
    hasPin,
    limits,
    paymentMethods,
    accountName,
}: {
    balance: number;
    hasPin: boolean;
    limits: { min: number; max: number };
    paymentMethods: SelectOption[];
    accountName: string;
}) {
    const form = useForm({
        amount: '',
        payment_method: 'cash',
        reason: '',
        bank_name: '',
        account_number: '',
        account_name: accountName,
        pin: '',
    });
    const kobo = toKobo(form.data.amount);
    const amountProblem =
        form.data.amount === ''
            ? null
            : kobo === null
              ? 'Enter an amount in naira, e.g. 5000.'
              : kobo < limits.min
                ? `The smallest withdrawal is ${formatNaira(limits.min)}.`
                : kobo > limits.max
                  ? `The largest single withdrawal is ${formatNaira(limits.max)}.`
                  : kobo > balance
                    ? `You only have ${formatNaira(balance)} in your wallet.`
                    : null;
    const byBank = form.data.payment_method === 'bank_transfer';

    const submit = (event: React.FormEvent) => {
        event.preventDefault();
        form.submit(WithdrawalController.store(), {
            onFinish: () => form.reset('pin'),
        });
    };

    return (
        <>
            <Head title="Request withdrawal" />

            <MemberPage
                title="Request withdrawal"
                description="The amount is held in your wallet straight away and paid once our staff approve it."
            >
                <form onSubmit={submit} className="grid max-w-2xl gap-5">
                    <section className="flex items-center justify-between gap-3 rounded-landing-lg bg-linear-to-br from-brand to-brand-dark p-4 text-white shadow-landing">
                        <span className="text-sm text-white/75">
                            Available in your wallet
                        </span>
                        <span className="font-display text-xl font-semibold tabular-nums">
                            {formatNaira(balance)}
                        </span>
                    </section>

                    <section className="grid gap-4 rounded-landing-lg border border-surface-200 bg-white p-5 sm:p-6">
                        <div className="grid 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="20000"
                                aria-invalid={
                                    form.errors.amount || amountProblem
                                        ? true
                                        : undefined
                                }
                            />
                            <InputError
                                message={
                                    form.errors.amount ??
                                    amountProblem ??
                                    undefined
                                }
                            />
                        </div>

                        <fieldset className="grid gap-2">
                            <legend className="mb-2 text-sm font-medium text-ink">
                                How you want it
                            </legend>
                            <div className="grid grid-cols-2 gap-2">
                                {paymentMethods.map((method) => {
                                    const Icon =
                                        method.value === 'cash'
                                            ? Banknote
                                            : Landmark;
                                    const isSelected =
                                        form.data.payment_method ===
                                        method.value;

                                    return (
                                        <label
                                            key={method.value}
                                            className={cn(
                                                'flex cursor-pointer items-center gap-2 rounded-landing border bg-white p-3 text-sm font-semibold text-ink has-focus-visible:ring-2 has-focus-visible:ring-highlight',
                                                isSelected
                                                    ? 'border-brand ring-2 ring-brand/15'
                                                    : 'border-surface-200 hover:border-brand/40',
                                            )}
                                        >
                                            <input
                                                type="radio"
                                                name="payment_method"
                                                value={method.value}
                                                checked={isSelected}
                                                onChange={() =>
                                                    form.setData(
                                                        'payment_method',
                                                        method.value,
                                                    )
                                                }
                                                className="sr-only"
                                            />
                                            <Icon className="size-5 text-brand" />
                                            {method.label}
                                        </label>
                                    );
                                })}
                            </div>
                            <InputError message={form.errors.payment_method} />
                        </fieldset>

                        {byBank && (
                            <div className="grid gap-4 rounded-landing bg-surface-50 p-4 sm:grid-cols-2">
                                <div className="grid content-start gap-2">
                                    <Label htmlFor="bank_name" required>
                                        Bank
                                    </Label>
                                    <Input
                                        id="bank_name"
                                        value={form.data.bank_name}
                                        onChange={(event) =>
                                            form.setData(
                                                'bank_name',
                                                event.target.value,
                                            )
                                        }
                                        maxLength={80}
                                        placeholder="e.g. Jaiz Bank"
                                    />
                                    <InputError
                                        message={form.errors.bank_name}
                                    />
                                </div>
                                <div className="grid content-start gap-2">
                                    <Label htmlFor="account_number" required>
                                        Account number
                                    </Label>
                                    <Input
                                        id="account_number"
                                        value={form.data.account_number}
                                        onChange={(event) =>
                                            form.setData(
                                                'account_number',
                                                event.target.value
                                                    .replace(/\D/g, '')
                                                    .slice(0, 10),
                                            )
                                        }
                                        inputMode="numeric"
                                        placeholder="10 digits"
                                    />
                                    <InputError
                                        message={form.errors.account_number}
                                    />
                                </div>
                                <div className="grid content-start gap-2 sm:col-span-2">
                                    <Label htmlFor="account_name" required>
                                        Name on the account
                                    </Label>
                                    <Input
                                        id="account_name"
                                        value={form.data.account_name}
                                        onChange={(event) =>
                                            form.setData(
                                                'account_name',
                                                event.target.value,
                                            )
                                        }
                                        maxLength={120}
                                    />
                                    <p className="text-xs text-ink-400">
                                        We only pay into an account in your own
                                        name.
                                    </p>
                                    <InputError
                                        message={form.errors.account_name}
                                    />
                                </div>
                            </div>
                        )}

                        <div className="grid gap-2">
                            <Label htmlFor="reason" required>
                                Reason
                            </Label>
                            <Input
                                id="reason"
                                value={form.data.reason}
                                onChange={(event) =>
                                    form.setData('reason', event.target.value)
                                }
                                maxLength={255}
                                placeholder="e.g. School fees"
                            />
                            <InputError message={form.errors.reason} />
                        </div>

                        <PinField
                            hasPin={hasPin}
                            value={form.data.pin}
                            error={form.errors.pin}
                            onChange={(pin) => form.setData('pin', pin)}
                        />
                    </section>

                    <p className="flex items-start gap-2 text-xs text-ink-400">
                        <ShieldCheck className="mt-0.5 size-4 shrink-0 text-highlight-dark" />
                        If the request is not approved, or you cancel it before
                        staff act on it, the money goes straight back to your
                        wallet.
                    </p>

                    <div className="flex items-center gap-2">
                        <Button
                            disabled={
                                form.processing ||
                                !hasPin ||
                                kobo === null ||
                                amountProblem !== null ||
                                form.data.reason.trim().length < 3 ||
                                form.data.pin.length !== 4
                            }
                        >
                            Request withdrawal
                        </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>
        </>
    );
}

WithdrawalsCreate.layout = {
    breadcrumbs: [
        { title: 'Withdrawals', href: index() },
        { title: 'Request', href: create() },
    ],
};
