import { Head, useForm } from '@inertiajs/react';
import { ArrowLeft, ArrowRight, Check, Hash } from 'lucide-react';
import { useState } from 'react';
import type { FormEvent } from 'react';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import {
    HowItWorks,
    PinField,
    RecipientCard,
    TransferBalance,
    TransferSteps,
    TransferSummary,
    amountProblem,
    toKobo,
    transferInputClasses,
    transferPrimaryButton,
} from '@/components/member/transfer-parts';
import type { TransferLimits } from '@/components/member/transfer-parts';
import { Spinner } from '@/components/ui/spinner';
import { formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { dashboard } from '@/routes';
import { create, recipient as recipientRoute, store } from '@/routes/transfers';
import { RequiredMark } from '@/components/required-mark';

type Props = {
    balance: number;
    hasPin: boolean;
    limits: TransferLimits;
};

type Recipient = { name: string; accountNumber: string };

const steps = ['Recipient', 'Amount', 'Confirm'] as const;

export default function TransferCreate({ balance, hasPin, limits }: Props) {
    const [step, setStep] = useState(0);
    const [recipient, setRecipient] = useState<Recipient | null>(null);
    const [lookupError, setLookupError] = useState<string | null>(null);
    const [isLookingUp, setIsLookingUp] = useState(false);

    const form = useForm({
        account_number: '',
        amount: '',
        narration: '',
        pin: '',
    });

    const amountKobo = toKobo(form.data.amount);
    const problem = amountProblem(form.data.amount, balance, limits);

    const lookUpAccount = async (event: FormEvent) => {
        event.preventDefault();
        setLookupError(null);
        setIsLookingUp(true);

        // Remember exactly what was checked, so later edits cannot change the destination.
        const checkedAccount = form.data.account_number;

        try {
            const response = await fetch(
                recipientRoute.url({
                    query: { account_number: checkedAccount },
                }),
                {
                    headers: {
                        Accept: 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                },
            );
            const body = await response.json();

            if (!response.ok) {
                setLookupError(
                    body.errors?.account_number?.[0] ??
                        body.message ??
                        'We could not check this account. Try again.',
                );

                return;
            }

            setRecipient({
                ...(body as Recipient),
                accountNumber: checkedAccount,
            });
            setStep(1);
        } catch {
            setLookupError(
                'We could not check this account. Check your connection and try again.',
            );
        } finally {
            setIsLookingUp(false);
        }
    };

    const send = (event: FormEvent) => {
        event.preventDefault();
        if (!recipient) {
            return;
        }

        form.transform((data) => ({
            ...data,
            account_number: recipient.accountNumber,
        }));
        form.post(store.url(), {
            preserveScroll: true,
            onError: (errors) => {
                form.setData('pin', '');

                if (errors.account_number) {
                    setRecipient(null);
                    setStep(0);
                } else if (errors.amount || errors.narration) {
                    setStep(1);
                }
            },
        });
    };

    return (
        <>
            <Head title="Transfer" />

            <MemberPage
                title="Transfer money"
                description="Send money instantly to another Smart Save member."
            >
                <div className="mx-auto grid w-full max-w-5xl gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)] lg:items-start">
                    <div className="flex min-w-0 flex-col gap-4">
                        <section className="rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm sm:p-6">
                            <TransferBalance balance={balance} />

                            <>
                                <TransferSteps steps={steps} current={step} />

                                {step === 0 && (
                                    <form
                                        onSubmit={lookUpAccount}
                                        className="mt-5 flex flex-col gap-4"
                                    >
                                        <div className="flex flex-col gap-2">
                                            <label
                                                htmlFor="account_number"
                                                className="text-sm font-semibold text-ink-700"
                                            >
                                                Recipient account number
                                                <RequiredMark />
                                            </label>
                                            <div className="relative">
                                                <Hash className="pointer-events-none absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-ink-300" />
                                                <input
                                                    id="account_number"
                                                    disabled={isLookingUp}
                                                    inputMode="numeric"
                                                    autoComplete="off"
                                                    maxLength={10}
                                                    placeholder="10-digit account number"
                                                    value={
                                                        form.data.account_number
                                                    }
                                                    onChange={(event) => {
                                                        form.setData(
                                                            'account_number',
                                                            event.target.value
                                                                .replace(
                                                                    /\D/g,
                                                                    '',
                                                                )
                                                                .slice(0, 10),
                                                        );
                                                        setLookupError(null);
                                                    }}
                                                    aria-invalid={
                                                        lookupError ||
                                                        form.errors
                                                            .account_number
                                                            ? true
                                                            : undefined
                                                    }
                                                    className={cn(
                                                        transferInputClasses,
                                                        'pl-10 font-mono tracking-[0.12em]',
                                                    )}
                                                />
                                            </div>
                                            <p className="text-xs text-ink-400">
                                                We show you the account name
                                                before you send anything.
                                            </p>
                                            <InputError
                                                message={
                                                    lookupError ??
                                                    form.errors.account_number
                                                }
                                            />
                                        </div>

                                        <button
                                            type="submit"
                                            disabled={
                                                form.data.account_number
                                                    .length !== 10 ||
                                                isLookingUp
                                            }
                                            className={transferPrimaryButton}
                                        >
                                            {isLookingUp && <Spinner />}
                                            Continue
                                            <ArrowRight className="size-4" />
                                        </button>
                                    </form>
                                )}

                                {step === 1 && recipient && (
                                    <form
                                        onSubmit={(event) => {
                                            event.preventDefault();
                                            setStep(2);
                                        }}
                                        className="mt-5 flex flex-col gap-4"
                                    >
                                        <RecipientCard
                                            name={recipient.name}
                                            detail={recipient.accountNumber}
                                            onChange={() => {
                                                setRecipient(null);
                                                setStep(0);
                                            }}
                                        />

                                        <div className="flex flex-col gap-2">
                                            <label
                                                htmlFor="amount"
                                                className="text-sm font-semibold text-ink-700"
                                            >
                                                Amount
                                                <RequiredMark />
                                            </label>
                                            <NairaInput
                                                id="amount"
                                                autoFocus
                                                placeholder={`Minimum ${formatNaira(limits.min)}`}
                                                value={form.data.amount}
                                                onChange={(event) =>
                                                    form.setData(
                                                        'amount',
                                                        event.target.value.replace(
                                                            /[^\d.]/g,
                                                            '',
                                                        ),
                                                    )
                                                }
                                                aria-invalid={
                                                    problem ||
                                                    form.errors.amount
                                                        ? true
                                                        : undefined
                                                }
                                                className="h-11 rounded-landing text-[15px]"
                                            />
                                            <p className="text-xs text-ink-400">
                                                {formatNaira(limits.min)} to{' '}
                                                {formatNaira(limits.max)} per
                                                transfer ·{' '}
                                                {formatNaira(
                                                    limits.remainingToday,
                                                )}{' '}
                                                left today
                                            </p>
                                            <InputError
                                                message={
                                                    problem ??
                                                    form.errors.amount
                                                }
                                            />
                                        </div>

                                        <div className="flex flex-col gap-2">
                                            <label
                                                htmlFor="narration"
                                                className="text-sm font-semibold text-ink-700"
                                            >
                                                Narration{' '}
                                                <span className="font-normal text-ink-400">
                                                    (optional)
                                                </span>
                                            </label>
                                            <input
                                                id="narration"
                                                maxLength={100}
                                                placeholder="What is it for?"
                                                value={form.data.narration}
                                                onChange={(event) =>
                                                    form.setData(
                                                        'narration',
                                                        event.target.value,
                                                    )
                                                }
                                                className={transferInputClasses}
                                            />
                                            <InputError
                                                message={form.errors.narration}
                                            />
                                        </div>

                                        <button
                                            type="submit"
                                            disabled={
                                                amountKobo === null ||
                                                problem !== null
                                            }
                                            className={transferPrimaryButton}
                                        >
                                            Review transfer
                                            <ArrowRight className="size-4" />
                                        </button>
                                    </form>
                                )}

                                {step === 2 &&
                                    recipient &&
                                    amountKobo !== null && (
                                        <form
                                            onSubmit={send}
                                            className="mt-5 flex flex-col gap-4"
                                        >
                                            <TransferSummary
                                                rows={[
                                                    ['To', recipient.name],
                                                    [
                                                        'Account',
                                                        recipient.accountNumber,
                                                    ],
                                                    [
                                                        'Amount',
                                                        formatNaira(amountKobo),
                                                    ],
                                                    ['Fee', formatNaira(0)],
                                                    ...(form.data.narration.trim()
                                                        ? ([
                                                              [
                                                                  'Narration',
                                                                  form.data.narration.trim(),
                                                              ],
                                                          ] as [
                                                              string,
                                                              string,
                                                          ][])
                                                        : []),
                                                ]}
                                                balanceAfter={
                                                    balance - amountKobo
                                                }
                                            />

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

                                            <div className="flex flex-col-reverse gap-2 sm:flex-row">
                                                <button
                                                    type="button"
                                                    onClick={() => setStep(1)}
                                                    className="inline-flex h-11 items-center justify-center gap-2 rounded-full px-5 text-sm font-semibold text-ink-500 hover:text-brand sm:w-auto"
                                                >
                                                    <ArrowLeft className="size-4" />
                                                    Back
                                                </button>
                                                <button
                                                    type="submit"
                                                    disabled={
                                                        !hasPin ||
                                                        form.data.pin.length !==
                                                            4 ||
                                                        form.processing
                                                    }
                                                    className={
                                                        transferPrimaryButton
                                                    }
                                                >
                                                    {form.processing ? (
                                                        <Spinner />
                                                    ) : (
                                                        <Check className="size-4" />
                                                    )}
                                                    Send{' '}
                                                    {formatNaira(amountKobo)}
                                                </button>
                                            </div>
                                        </form>
                                    )}
                            </>
                        </section>
                    </div>

                    <HowItWorks
                        title="How member transfers work"
                        steps={[
                            "Enter the member's 10-digit Smart Save account number.",
                            'Check the account name we show you before you continue.',
                            `Enter the amount (from ${formatNaira(limits.min)}) and an optional narration.`,
                            'Review the details and confirm with your transaction PIN.',
                            'The money arrives instantly and the member is notified. There is no fee.',
                        ]}
                    />
                </div>
            </MemberPage>
        </>
    );
}

TransferCreate.layout = {
    breadcrumbs: [
        { title: 'Dashboard', href: dashboard() },
        { title: 'Transfer', href: create() },
    ],
};
