import { Head, Link, useForm } from '@inertiajs/react';
import {
    ArrowLeft,
    ArrowRight,
    Banknote,
    Check,
    Circle,
    CircleCheck,
    CreditCard,
    Landmark,
    Loader2,
    PiggyBank,
    Search,
    ShieldCheck,
    Wallet,
    X,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import DepositController from '@/actions/App/Http/Controllers/Admin/DepositController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import StatusBadge from '@/components/member/status-badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useInitials } from '@/hooks/use-initials';
import { formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import {
    create,
    index,
    members as membersRoute,
} from '@/routes/admin/deposits';
import type { SelectOption } from '@/types';

type MemberMatch = {
    id: number;
    name: string;
    memberId: string;
    email: string;
    membershipStatus: string;
    membershipStatusLabel: string;
    isSelf: boolean;
    plans: { id: number; name: string; balance: number }[];
};

const methodIcons: Record<string, typeof Banknote> = {
    cash: Banknote,
    bank_transfer: Landmark,
    pos: CreditCard,
};

export default function DepositsCreate({
    paymentMethods,
    limits,
    preselected,
    preselectedPlanId,
    suggestedAmount,
}: {
    paymentMethods: SelectOption[];
    limits: { min: number; max: number };
    preselected: MemberMatch | null;
    preselectedPlanId: number | null;
    suggestedAmount: number | null;
}) {
    const [query, setQuery] = useState('');
    const [matches, setMatches] = useState<MemberMatch[]>([]);
    const [isSearching, setIsSearching] = useState(false);
    const [member, setMember] = useState<MemberMatch | null>(preselected);
    const [isConfirming, setIsConfirming] = useState(false);
    const latestQuery = useRef('');
    const getInitials = useInitials();

    const form = useForm({
        member_id: preselected ? String(preselected.id) : '',
        amount: suggestedAmount ? String(suggestedAmount / 100) : '',
        payment_method: 'cash',
        savings_plan_id: preselectedPlanId ? String(preselectedPlanId) : '',
        note: '',
    });

    useEffect(() => {
        const term = query.trim();
        latestQuery.current = term;

        if (member || term.length < 2) {
            setMatches([]);

            return;
        }

        const timer = window.setTimeout(async () => {
            setIsSearching(true);

            try {
                const response = await fetch(
                    membersRoute.url({ query: { q: term } }),
                    {
                        headers: {
                            Accept: 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                    },
                );
                const body = (await response.json()) as {
                    members?: MemberMatch[];
                };

                if (latestQuery.current === term) {
                    setMatches(body.members ?? []);
                }
            } catch {
                setMatches([]);
            } finally {
                setIsSearching(false);
            }
        }, 300);

        return () => window.clearTimeout(timer);
    }, [query, member]);

    const choose = (match: MemberMatch) => {
        setMember(match);
        setMatches([]);
        form.setData((data) => ({
            ...data,
            member_id: String(match.id),
            savings_plan_id: '',
        }));
        form.clearErrors('member_id');
    };

    const clearMember = () => {
        setMember(null);
        setQuery('');
        setIsConfirming(false);
        form.setData((data) => ({
            ...data,
            member_id: '',
            savings_plan_id: '',
        }));
    };

    const amountNumber = Number(form.data.amount);
    const amountKobo = Math.round(amountNumber * 100);
    const amountProblem =
        form.data.amount === ''
            ? 'Enter the amount received.'
            : !Number.isFinite(amountNumber) || amountKobo < limits.min
              ? `The smallest deposit is ${formatNaira(limits.min)}.`
              : amountKobo > limits.max
                ? `The largest single deposit is ${formatNaira(limits.max)}.`
                : null;
    const memberProblem = !member
        ? 'Choose the member first.'
        : member.isSelf
          ? 'Another member of staff must record your own deposits.'
          : member.membershipStatus !== 'active'
            ? `This membership is ${member.membershipStatusLabel.toLowerCase()}.`
            : null;
    const plan = member?.plans.find(
        (item) => String(item.id) === form.data.savings_plan_id,
    );
    const methodLabel =
        paymentMethods.find(
            (method) => method.value === form.data.payment_method,
        )?.label ?? '';

    const submit = () => {
        form.submit(DepositController.store(), {
            onError: () => setIsConfirming(false),
        });
    };

    const quickAmounts = [100_000, 500_000, 1_000_000, 2_000_000].filter(
        (kobo) => kobo >= limits.min && kobo <= limits.max,
    );
    const checks = [
        { label: 'Member chosen', done: Boolean(member) && !memberProblem },
        { label: 'Amount entered', done: !amountProblem },
        { label: 'Payment method', done: methodLabel !== '' },
    ];

    return (
        <>
            <Head title="Record deposit" />

            <MemberPage
                title="Record deposit"
                description="For money the member has handed over. It is added to their account straight away."
                actions={
                    <Link
                        href={index()}
                        className="inline-flex items-center gap-1.5 rounded-full border border-surface-200 bg-white px-3.5 py-1.5 text-sm font-semibold text-ink-700 hover:border-brand/40"
                    >
                        <ArrowLeft className="size-4" />
                        All deposits
                    </Link>
                }
            >
                <div className="grid max-w-5xl items-start gap-4 lg:grid-cols-[minmax(0,1fr)_18rem]">
                    <div className="grid gap-3">
                        <Step number={1} title="Member" done={checks[0].done}>
                            {member ? (
                                <div className="flex items-center gap-3 rounded-landing border border-brand/20 bg-linear-to-r from-brand-faint to-white px-3 py-2.5">
                                    <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-brand text-xs font-semibold text-white">
                                        {getInitials(member.name)}
                                    </span>
                                    <div className="min-w-0 flex-1">
                                        <p className="truncate text-sm font-semibold text-ink">
                                            {member.name}
                                        </p>
                                        <p className="truncate text-xs text-ink-500">
                                            <span className="font-mono">
                                                {member.memberId}
                                            </span>{' '}
                                            · {member.email}
                                        </p>
                                    </div>
                                    {member.membershipStatus !== 'active' && (
                                        <StatusBadge tone="failed">
                                            {member.membershipStatusLabel}
                                        </StatusBadge>
                                    )}
                                    <button
                                        type="button"
                                        onClick={clearMember}
                                        className="inline-flex items-center gap-1 rounded-full px-3 py-1.5 text-xs font-semibold text-ink-500 hover:bg-white hover:text-ink"
                                    >
                                        <X className="size-3.5" />
                                        Change
                                    </button>
                                </div>
                            ) : (
                                <div>
                                    <Label htmlFor="member-search" required>
                                        Find the member
                                    </Label>
                                    <div className="relative mt-2">
                                        <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-ink-400" />
                                        <Input
                                            id="member-search"
                                            value={query}
                                            onChange={(event) =>
                                                setQuery(event.target.value)
                                            }
                                            placeholder="Name, email, phone or ADS-000125"
                                            autoComplete="off"
                                            autoFocus
                                            className="h-10 pl-9"
                                            aria-describedby="member-search-hint"
                                        />
                                        {isSearching && (
                                            <Loader2 className="absolute top-1/2 right-3 size-4 -translate-y-1/2 animate-spin text-ink-400" />
                                        )}
                                    </div>
                                    <p
                                        id="member-search-hint"
                                        className="mt-1.5 text-xs text-ink-400"
                                    >
                                        Check the name with the member before
                                        you continue.
                                    </p>
                                    {matches.length > 0 && (
                                        <ul className="mt-2 grid gap-1">
                                            {matches.map((match) => (
                                                <li key={match.id}>
                                                    <button
                                                        type="button"
                                                        onClick={() =>
                                                            choose(match)
                                                        }
                                                        className="flex w-full items-center gap-2.5 rounded-landing border border-surface-200 bg-white px-2.5 py-2 text-left transition hover:-translate-y-px hover:border-brand/40 hover:shadow-landing-sm"
                                                    >
                                                        <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-brand-faint text-[11px] font-semibold text-brand">
                                                            {getInitials(
                                                                match.name,
                                                            )}
                                                        </span>
                                                        <span className="min-w-0 flex-1">
                                                            <span className="block truncate text-sm font-semibold text-ink">
                                                                {match.name}
                                                            </span>
                                                            <span className="block truncate text-xs text-ink-400">
                                                                <span className="font-mono">
                                                                    {
                                                                        match.memberId
                                                                    }
                                                                </span>{' '}
                                                                · {match.email}
                                                            </span>
                                                        </span>
                                                        {match.membershipStatus !==
                                                            'active' && (
                                                            <StatusBadge tone="failed">
                                                                {
                                                                    match.membershipStatusLabel
                                                                }
                                                            </StatusBadge>
                                                        )}
                                                    </button>
                                                </li>
                                            ))}
                                        </ul>
                                    )}
                                    {!isSearching &&
                                        query.trim().length >= 2 &&
                                        matches.length === 0 && (
                                            <p className="mt-3 rounded-landing bg-surface-50 px-3 py-2.5 text-sm text-ink-500">
                                                No member matches “
                                                {query.trim()}”.
                                            </p>
                                        )}
                                </div>
                            )}
                            <InputError
                                message={
                                    form.errors.member_id ??
                                    (member
                                        ? (memberProblem ?? undefined)
                                        : undefined)
                                }
                            />
                        </Step>

                        <Step number={2} title="Payment" done={checks[1].done}>
                            <div className="grid gap-2">
                                <Label htmlFor="amount" required>
                                    Amount received
                                </Label>
                                <div className="relative">
                                    <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-lg text-ink-400">
                                        ₦
                                    </span>
                                    <input
                                        id="amount"
                                        inputMode="decimal"
                                        value={form.data.amount}
                                        onChange={(event) =>
                                            form.setData(
                                                'amount',
                                                event.target.value.replace(
                                                    /[^\d.]/g,
                                                    '',
                                                ),
                                            )
                                        }
                                        placeholder="0.00"
                                        aria-invalid={
                                            form.errors.amount
                                                ? true
                                                : undefined
                                        }
                                        className="h-11 w-full rounded-md border border-input bg-white pr-3 pl-8 font-display text-xl font-semibold text-ink tabular-nums shadow-xs outline-none placeholder:text-ink-300 focus-visible:border-brand focus-visible:ring-3 focus-visible:ring-brand/15"
                                    />
                                </div>
                                {quickAmounts.length > 0 && (
                                    <div className="flex flex-wrap gap-2">
                                        {quickAmounts.map((kobo) => (
                                            <button
                                                key={kobo}
                                                type="button"
                                                onClick={() =>
                                                    form.setData(
                                                        'amount',
                                                        String(kobo / 100),
                                                    )
                                                }
                                                className={cn(
                                                    'rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors',
                                                    amountKobo === kobo
                                                        ? 'border-brand bg-brand text-white'
                                                        : 'border-surface-200 bg-white text-ink-700 hover:border-brand/40',
                                                )}
                                            >
                                                {formatNaira(kobo)}
                                            </button>
                                        ))}
                                    </div>
                                )}
                                <p className="text-xs text-ink-400">
                                    Between {formatNaira(limits.min)} and{' '}
                                    {formatNaira(limits.max)} per deposit.
                                </p>
                                <InputError message={form.errors.amount} />
                            </div>

                            <fieldset className="grid gap-2">
                                <legend className="mb-1.5 text-sm font-medium text-ink">
                                    Paid by
                                </legend>
                                <div className="grid grid-cols-3 gap-2">
                                    {paymentMethods.map((method) => {
                                        const Icon =
                                            methodIcons[method.value] ??
                                            Banknote;
                                        const selected =
                                            form.data.payment_method ===
                                            method.value;

                                        return (
                                            <label
                                                key={method.value}
                                                className={cn(
                                                    'relative flex cursor-pointer items-center justify-center gap-2 rounded-landing border bg-white px-2 py-2 text-sm font-semibold text-ink transition has-focus-visible:ring-2 has-focus-visible:ring-highlight',
                                                    selected
                                                        ? 'border-brand bg-brand-faint/50 ring-2 ring-brand/15'
                                                        : 'border-surface-200 hover:-translate-y-px hover:border-brand/40',
                                                )}
                                            >
                                                <input
                                                    type="radio"
                                                    name="payment_method"
                                                    value={method.value}
                                                    checked={selected}
                                                    onChange={() =>
                                                        form.setData(
                                                            'payment_method',
                                                            method.value,
                                                        )
                                                    }
                                                    className="sr-only"
                                                />
                                                {selected && (
                                                    <CircleCheck className="absolute top-1 right-1 size-3.5 text-brand" />
                                                )}
                                                <span
                                                    className={cn(
                                                        'flex size-7 items-center justify-center rounded-full',
                                                        selected
                                                            ? 'bg-brand text-white'
                                                            : 'bg-brand-faint text-brand',
                                                    )}
                                                >
                                                    <Icon className="size-4" />
                                                </span>
                                                {method.label}
                                            </label>
                                        );
                                    })}
                                </div>
                                <InputError
                                    message={form.errors.payment_method}
                                />
                            </fieldset>

                            <div className="grid gap-2">
                                <Label htmlFor="note">
                                    Note or bank reference
                                </Label>
                                <Input
                                    id="note"
                                    value={form.data.note}
                                    onChange={(event) =>
                                        form.setData('note', event.target.value)
                                    }
                                    maxLength={255}
                                    placeholder="Optional, e.g. teller number"
                                    className="h-9"
                                />
                                <InputError message={form.errors.note} />
                            </div>
                        </Step>

                        <Step
                            number={3}
                            title="Where it goes"
                            done={Boolean(member)}
                        >
                            <div className="grid gap-2 sm:grid-cols-2">
                                <DestinationOption
                                    checked={form.data.savings_plan_id === ''}
                                    onChange={() =>
                                        form.setData('savings_plan_id', '')
                                    }
                                    icon={Wallet}
                                    title="Wallet"
                                    detail="The member can use it straight away."
                                />
                                {member?.plans.map((item) => (
                                    <DestinationOption
                                        key={item.id}
                                        checked={
                                            form.data.savings_plan_id ===
                                            String(item.id)
                                        }
                                        onChange={() =>
                                            form.setData(
                                                'savings_plan_id',
                                                String(item.id),
                                            )
                                        }
                                        icon={PiggyBank}
                                        title={item.name}
                                        detail={`Savings plan · ${formatNaira(item.balance)} saved`}
                                    />
                                ))}
                            </div>
                            {member && member.plans.length === 0 && (
                                <p className="text-xs text-ink-400">
                                    This member has no active savings plans.
                                </p>
                            )}
                            <InputError message={form.errors.savings_plan_id} />
                        </Step>
                    </div>

                    <aside className="lg:sticky lg:top-20">
                        <section className="overflow-hidden rounded-landing-lg bg-brand-dark text-white shadow-landing-sm">
                            <div className="bg-linear-to-br from-brand to-brand-dark px-5 py-4">
                                <p className="text-xs font-semibold tracking-widest text-white/60 uppercase">
                                    Deposit summary
                                </p>
                                <p className="mt-1 font-display text-2xl font-semibold tabular-nums">
                                    {amountProblem && form.data.amount === ''
                                        ? formatNaira(0)
                                        : formatNaira(
                                              Number.isFinite(amountKobo)
                                                  ? amountKobo
                                                  : 0,
                                          )}
                                </p>
                                <p className="mt-1 text-sm text-white/70">
                                    {methodLabel || 'Payment method'} ·{' '}
                                    {plan ? plan.name : 'Wallet'}
                                </p>
                            </div>

                            <dl className="grid gap-2 border-t border-white/10 px-5 py-4 text-sm">
                                <div className="flex justify-between gap-3">
                                    <dt className="text-white/60">Member</dt>
                                    <dd className="truncate text-right font-medium">
                                        {member
                                            ? `${member.name} · ${member.memberId}`
                                            : 'Not chosen'}
                                    </dd>
                                </div>
                                <div className="flex justify-between gap-3">
                                    <dt className="text-white/60">Into</dt>
                                    <dd className="text-right font-medium">
                                        {plan
                                            ? `${plan.name} (savings)`
                                            : 'Wallet'}
                                    </dd>
                                </div>
                                {form.data.note && (
                                    <div className="flex justify-between gap-3">
                                        <dt className="text-white/60">Note</dt>
                                        <dd className="truncate text-right font-medium">
                                            {form.data.note}
                                        </dd>
                                    </div>
                                )}
                            </dl>

                            <div className="grid gap-2.5 border-t border-white/10 px-5 py-4">
                                {!isConfirming ? (
                                    <>
                                        <ul className="grid gap-1 text-xs">
                                            {checks.map((check) => (
                                                <li
                                                    key={check.label}
                                                    className={cn(
                                                        'flex items-center gap-2',
                                                        check.done
                                                            ? 'text-white'
                                                            : 'text-white/50',
                                                    )}
                                                >
                                                    {check.done ? (
                                                        <CircleCheck className="size-4 text-highlight" />
                                                    ) : (
                                                        <Circle className="size-4" />
                                                    )}
                                                    {check.label}
                                                </li>
                                            ))}
                                        </ul>
                                        {(memberProblem || amountProblem) && (
                                            <p className="text-xs text-white/60">
                                                {memberProblem ?? amountProblem}
                                            </p>
                                        )}
                                        <Button
                                            type="button"
                                            disabled={Boolean(
                                                memberProblem || amountProblem,
                                            )}
                                            onClick={() =>
                                                setIsConfirming(true)
                                            }
                                            className="w-full bg-highlight text-white hover:bg-highlight/90"
                                        >
                                            Review deposit
                                            <ArrowRight className="size-4" />
                                        </Button>
                                    </>
                                ) : (
                                    <>
                                        <p className="flex items-start gap-2 rounded-landing bg-white/10 p-3 text-xs text-white/80">
                                            <ShieldCheck className="mt-0.5 size-4 shrink-0 text-highlight" />
                                            Only confirm once the money is in
                                            hand. The member is notified and the
                                            deposit cannot be undone here.
                                        </p>
                                        <Button
                                            type="button"
                                            onClick={submit}
                                            disabled={form.processing}
                                            className="w-full bg-highlight text-white hover:bg-highlight/90"
                                        >
                                            {form.processing && (
                                                <Loader2 className="size-4 animate-spin" />
                                            )}
                                            Confirm and record
                                        </Button>
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            onClick={() =>
                                                setIsConfirming(false)
                                            }
                                            className="w-full text-white/80 hover:bg-white/10 hover:text-white"
                                        >
                                            Back to edit
                                        </Button>
                                    </>
                                )}
                            </div>
                        </section>
                    </aside>
                </div>
            </MemberPage>
        </>
    );
}

function Step({
    number,
    title,
    done,
    children,
}: {
    number: number;
    title: string;
    done: boolean;
    children: React.ReactNode;
}) {
    return (
        <section className="grid gap-3 rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm">
            <h2 className="flex items-center gap-2 text-sm font-semibold text-ink">
                <span
                    className={cn(
                        'flex size-6 items-center justify-center rounded-full text-[11px] font-bold transition-colors',
                        done
                            ? 'bg-highlight text-white'
                            : 'bg-brand-faint text-brand',
                    )}
                >
                    {done ? <Check className="size-3.5" /> : number}
                </span>
                {title}
            </h2>
            {children}
        </section>
    );
}

function DestinationOption({
    checked,
    onChange,
    icon: Icon,
    title,
    detail,
}: {
    checked: boolean;
    onChange: () => void;
    icon: typeof Wallet;
    title: string;
    detail: string;
}) {
    return (
        <label
            className={cn(
                'flex cursor-pointer items-center gap-2.5 rounded-landing border bg-white px-3 py-2 transition-colors has-focus-visible:ring-2 has-focus-visible:ring-highlight',
                checked
                    ? 'border-brand ring-2 ring-brand/15'
                    : 'border-surface-200 hover:border-brand/40',
            )}
        >
            <input
                type="radio"
                name="destination"
                checked={checked}
                onChange={onChange}
                className="sr-only"
            />
            <span
                className={cn(
                    'flex size-7 shrink-0 items-center justify-center rounded-md',
                    checked
                        ? 'bg-brand text-white'
                        : 'bg-brand-faint text-brand',
                )}
            >
                <Icon className="size-3.5" />
            </span>
            <span className="min-w-0">
                <span className="block truncate text-sm font-semibold text-ink">
                    {title}
                </span>
                <span className="block truncate text-xs text-ink-400">
                    {detail}
                </span>
            </span>
        </label>
    );
}

DepositsCreate.layout = {
    breadcrumbs: [
        { title: 'Deposits', href: index() },
        { title: 'Record deposit', href: create() },
    ],
};
