import { Form, Head } from '@inertiajs/react';
import { Lock } from 'lucide-react';
import SavingsPlanController from '@/actions/App/Http/Controllers/SavingsPlanController';
import InputError from '@/components/input-error';
import MemberPage from '@/components/member/member-page';
import NairaInput from '@/components/member/naira-input';
import ProgressBar from '@/components/member/progress-bar';
import StatusBadge from '@/components/member/status-badge';
import TransactionList from '@/components/member/transaction-list';
import { Button } from '@/components/ui/button';
import { formatDate, formatNaira } from '@/lib/format';
import { index } from '@/routes/savings';
import type { SavingsPlanItem, TransactionItem } from '@/types';
import { RequiredMark } from '@/components/required-mark';

export default function SavingsShow({
    plan,
    walletBalance,
    movements,
}: {
    plan: SavingsPlanItem;
    walletBalance: number;
    movements: TransactionItem[];
}) {
    const isActive = plan.status === 'active';

    return (
        <>
            <Head title={plan.name} />

            <MemberPage
                title={plan.name}
                description={`${plan.typeLabel} · ${plan.reference}`}
                actions={
                    !isActive && (
                        <StatusBadge tone="neutral">Closed</StatusBadge>
                    )
                }
            >
                <div className="grid gap-4 lg:grid-cols-3">
                    <section className="rounded-landing-lg bg-brand-dark p-6 text-white lg:col-span-2">
                        <p className="text-sm text-white/70">Saved so far</p>
                        <p className="mt-2 font-display text-4xl font-semibold tabular-nums">
                            {formatNaira(plan.balance)}
                        </p>
                        <p className="mt-1 text-sm text-white/70">
                            of {formatNaira(plan.targetAmount)} target ·{' '}
                            {plan.progress}%
                        </p>
                        <div className="mt-4 [&>div]:bg-white/15">
                            <ProgressBar
                                value={plan.progress}
                                label="Progress to target"
                            />
                        </div>
                    </section>

                    <section className="rounded-landing-lg border border-surface-200 bg-white p-6">
                        <dl className="grid gap-3 text-sm">
                            {[
                                [
                                    'Contribution',
                                    `${formatNaira(plan.contributionAmount)} ${plan.frequencyLabel.toLowerCase()}`,
                                ],
                                ['Started', formatDate(plan.startDate)],
                                ['Matures', formatDate(plan.maturityDate)],
                                [
                                    'Next auto-save',
                                    plan.autoDebit
                                        ? formatDate(plan.nextDebitOn)
                                        : 'Off',
                                ],
                            ].map(([term, detail]) => (
                                <div
                                    key={term}
                                    className="flex justify-between gap-4"
                                >
                                    <dt className="text-ink-400">{term}</dt>
                                    <dd className="text-right font-medium text-ink">
                                        {detail}
                                    </dd>
                                </div>
                            ))}
                        </dl>
                        {isActive && (
                            <Form
                                {...SavingsPlanController.toggleAutoDebit.form(
                                    plan.id,
                                )}
                                options={{ preserveScroll: true }}
                                className="mt-4"
                            >
                                {({ processing }) => (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        disabled={processing}
                                    >
                                        {plan.autoDebit
                                            ? 'Turn off auto-save'
                                            : 'Turn on auto-save'}
                                    </Button>
                                )}
                            </Form>
                        )}
                    </section>
                </div>

                {isActive && (
                    <div className="grid gap-4 md:grid-cols-2">
                        <section className="rounded-landing-lg border border-surface-200 bg-white p-5">
                            <h2 className="font-semibold text-ink">
                                Add money
                            </h2>
                            <p className="mt-0.5 text-xs text-ink-400">
                                Wallet balance: {formatNaira(walletBalance)}
                            </p>
                            <Form
                                {...SavingsPlanController.deposit.form(plan.id)}
                                resetOnSuccess
                                options={{ preserveScroll: true }}
                                className="mt-3 grid gap-2"
                            >
                                {({ processing, errors }) => (
                                    <>
                                        <label
                                            htmlFor="deposit-amount"
                                            className="sr-only"
                                        >
                                            Amount to add
                                            <RequiredMark />
                                        </label>
                                        <div className="flex gap-2">
                                            <div className="flex-1">
                                                <NairaInput
                                                    id="deposit-amount"
                                                    name="amount"
                                                    required
                                                    placeholder="5000"
                                                />
                                            </div>
                                            <Button disabled={processing}>
                                                Add
                                            </Button>
                                        </div>
                                        <InputError message={errors.amount} />
                                    </>
                                )}
                            </Form>
                        </section>

                        <section className="rounded-landing-lg border border-surface-200 bg-white p-5">
                            <h2 className="font-semibold text-ink">
                                Withdraw to wallet
                            </h2>
                            {plan.canWithdraw ? (
                                <Form
                                    {...SavingsPlanController.withdraw.form(
                                        plan.id,
                                    )}
                                    resetOnSuccess
                                    options={{ preserveScroll: true }}
                                    className="mt-3 grid gap-2"
                                >
                                    {({ processing, errors }) => (
                                        <>
                                            <label
                                                htmlFor="withdraw-amount"
                                                className="sr-only"
                                            >
                                                Amount to withdraw
                                                <RequiredMark />
                                            </label>
                                            <div className="flex gap-2">
                                                <div className="flex-1">
                                                    <NairaInput
                                                        id="withdraw-amount"
                                                        name="amount"
                                                        required
                                                        placeholder="5000"
                                                    />
                                                </div>
                                                <Button
                                                    variant="outline"
                                                    disabled={processing}
                                                >
                                                    Withdraw
                                                </Button>
                                            </div>
                                            <InputError
                                                message={errors.amount}
                                            />
                                        </>
                                    )}
                                </Form>
                            ) : (
                                <p className="mt-3 flex items-start gap-2 text-sm text-ink-500">
                                    <Lock className="mt-0.5 size-4 shrink-0 text-ink-300" />
                                    {plan.withdrawalLockReason ??
                                        'Nothing to withdraw yet.'}
                                </p>
                            )}
                        </section>
                    </div>
                )}

                <section className="overflow-hidden rounded-landing-lg border border-surface-200 bg-white">
                    <h2 className="px-5 py-4 font-display text-lg font-semibold text-ink">
                        Plan activity
                    </h2>
                    {movements.length === 0 ? (
                        <p className="border-t border-surface-100 px-5 py-8 text-center text-sm text-ink-400">
                            No money has moved in or out of this plan yet.
                        </p>
                    ) : (
                        <div className="border-t border-surface-100">
                            <TransactionList transactions={movements} />
                        </div>
                    )}
                </section>
            </MemberPage>
        </>
    );
}

SavingsShow.layout = {
    breadcrumbs: [{ title: 'Savings', href: index() }],
};
