import { Head, Link } from '@inertiajs/react';
import {
    ArrowRight,
    CalendarClock,
    Plus,
    Repeat,
    ShieldAlert,
} from 'lucide-react';
import { useState } from 'react';
import MemberPage from '@/components/member/member-page';
import ProgressBar from '@/components/member/progress-bar';
import { savingsTypeStyle } from '@/components/member/savings-type-style';
import StatusBadge from '@/components/member/status-badge';
import { formatDate, formatNaira } from '@/lib/format';
import { cn } from '@/lib/utils';
import { show as kycShow } from '@/routes/kyc';
import { create, index, show } from '@/routes/savings';
import type { SavingsPlanItem } from '@/types';

type Summary = {
    total: number;
    targetTotal: number;
    savedTowardTargets: number;
    activeCount: number;
    nextAutoSave: { date: string; amount: number; planName: string } | null;
};

type PlanType = {
    value: string;
    label: string;
    description: string;
    rule: string;
};

function daysUntil(date: string): number {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    return Math.round(
        (new Date(`${date}T00:00:00`).getTime() - today.getTime()) / 86_400_000,
    );
}

export default function SavingsIndex({
    plans,
    summary,
    isVerified,
    types,
}: {
    plans: SavingsPlanItem[];
    summary: Summary;
    isVerified: boolean;
    types: PlanType[];
}) {
    const activePlans = plans.filter((plan) => plan.status !== 'closed');
    const closedPlans = plans.filter((plan) => plan.status === 'closed');
    const [tab, setTab] = useState<'active' | 'closed'>('active');
    const visiblePlans = tab === 'active' ? activePlans : closedPlans;
    const progress =
        summary.targetTotal > 0
            ? Math.min(
                  100,
                  Math.floor(
                      (summary.savedTowardTargets * 100) / summary.targetTotal,
                  ),
              )
            : 0;

    const newPlanButton = isVerified ? (
        <Link
            href={create()}
            className="inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
        >
            <Plus className="size-4" />
            New plan
        </Link>
    ) : (
        <Link
            href={kycShow()}
            className="inline-flex items-center gap-1.5 rounded-full bg-brand px-3.5 py-1.5 text-sm font-semibold text-white hover:bg-brand-hover"
        >
            <ShieldAlert className="size-4" />
            Verify to start saving
        </Link>
    );

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

            <MemberPage
                title="Savings"
                description="Transparent plans that help you save with purpose."
                actions={newPlanButton}
            >
                <section
                    aria-label="Savings summary"
                    className="relative overflow-hidden rounded-landing-lg bg-linear-to-br from-brand to-brand-dark p-4 text-white shadow-landing sm:p-5"
                >
                    <div
                        aria-hidden="true"
                        className="pointer-events-none absolute -top-24 -right-20 size-72 rounded-full bg-white/5"
                    />
                    <p className="relative text-sm text-white/75">
                        Total in active plans
                    </p>
                    <p className="relative mt-1 font-display text-2xl font-semibold tracking-[-0.02em] tabular-nums sm:text-3xl">
                        {formatNaira(summary.total)}
                    </p>
                    {summary.activeCount > 0 && (
                        <div className="relative mt-3 max-w-md">
                            <div className="h-1.5 overflow-hidden rounded-full bg-white/15">
                                <div
                                    className="h-full rounded-full bg-highlight"
                                    style={{ width: `${progress}%` }}
                                />
                            </div>
                            <p className="mt-1.5 text-xs text-white/70">
                                {progress}% of{' '}
                                {formatNaira(summary.targetTotal)} across your
                                targets
                            </p>
                        </div>
                    )}

                    <dl className="relative mt-4 grid grid-cols-1 gap-2 sm:grid-cols-3">
                        <div className="rounded-landing bg-white/8 px-3 py-2.5 ring-1 ring-white/10">
                            <dt className="text-xs text-white/60">
                                Active plans
                            </dt>
                            <dd className="mt-0.5 text-sm font-semibold">
                                {summary.activeCount}
                            </dd>
                        </div>
                        <div className="rounded-landing bg-white/8 px-3 py-2.5 ring-1 ring-white/10">
                            <dt className="text-xs text-white/60">
                                Left to reach targets
                            </dt>
                            <dd className="mt-0.5 text-sm font-semibold tabular-nums">
                                {formatNaira(
                                    Math.max(
                                        0,
                                        summary.targetTotal -
                                            summary.savedTowardTargets,
                                    ),
                                )}
                            </dd>
                        </div>
                        <div className="rounded-landing bg-white/8 px-3 py-2.5 ring-1 ring-white/10">
                            <dt className="text-xs text-white/60">
                                Next auto-save
                            </dt>
                            <dd className="mt-0.5 truncate text-sm font-semibold">
                                {summary.nextAutoSave
                                    ? `${formatNaira(summary.nextAutoSave.amount)} · ${formatDate(summary.nextAutoSave.date)}`
                                    : 'None scheduled'}
                            </dd>
                        </div>
                    </dl>
                </section>

                {plans.length === 0 ? (
                    <section className="rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm sm:p-5">
                        <h2 className="font-display text-base font-semibold text-ink">
                            Start your first plan
                        </h2>
                        <p className="mt-1 text-sm text-ink-400">
                            {isVerified
                                ? 'Pick the kind of saving that fits your goal.'
                                : 'Verify your identity, then pick the kind of saving that fits your goal.'}
                        </p>
                        <ul className="mt-4 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
                            {types.map((type) => {
                                const style = savingsTypeStyle(type.rule);

                                return (
                                    <li key={type.value}>
                                        <Link
                                            href={
                                                isVerified
                                                    ? create()
                                                    : kycShow()
                                            }
                                            className="flex h-full items-start gap-3 rounded-landing border border-surface-200 p-3 transition-colors hover:border-brand/40 hover:bg-surface-50"
                                        >
                                            <span
                                                className={cn(
                                                    'flex size-9 shrink-0 items-center justify-center rounded-landing',
                                                    style.tone,
                                                )}
                                            >
                                                <style.icon className="size-4" />
                                            </span>
                                            <span className="min-w-0">
                                                <span className="block text-sm font-semibold text-ink">
                                                    {type.label}
                                                </span>
                                                <span className="mt-0.5 block text-xs leading-relaxed text-ink-400">
                                                    {type.description}
                                                </span>
                                            </span>
                                        </Link>
                                    </li>
                                );
                            })}
                        </ul>
                    </section>
                ) : (
                    <section className="flex flex-col gap-3">
                        <div
                            role="tablist"
                            aria-label="Plans"
                            className="inline-flex w-fit gap-1 rounded-full bg-surface-100 p-1"
                        >
                            {(
                                [
                                    ['active', 'Active', activePlans.length],
                                    ['closed', 'Closed', closedPlans.length],
                                ] as const
                            ).map(([key, label, count]) => (
                                <button
                                    key={key}
                                    type="button"
                                    role="tab"
                                    aria-selected={tab === key}
                                    onClick={() => setTab(key)}
                                    className={cn(
                                        'rounded-full px-3.5 py-1.5 text-sm font-semibold transition-colors focus-visible:ring-2 focus-visible:ring-highlight focus-visible:outline-none',
                                        tab === key
                                            ? 'bg-white text-ink shadow-landing-sm'
                                            : 'text-ink-500 hover:text-ink',
                                    )}
                                >
                                    {label}{' '}
                                    <span className="text-ink-400">
                                        {count}
                                    </span>
                                </button>
                            ))}
                        </div>

                        {visiblePlans.length === 0 ? (
                            <p className="rounded-landing-lg border border-dashed border-surface-200 bg-white px-4 py-8 text-center text-sm text-ink-400">
                                {tab === 'active'
                                    ? 'No active plans. Start a new one to keep saving.'
                                    : 'No closed plans yet.'}
                            </p>
                        ) : (
                            <ul className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
                                {visiblePlans.map((plan) => (
                                    <li key={plan.id} className="min-w-0">
                                        <PlanCard plan={plan} />
                                    </li>
                                ))}
                            </ul>
                        )}
                    </section>
                )}
            </MemberPage>
        </>
    );
}

function PlanCard({ plan }: { plan: SavingsPlanItem }) {
    const style = savingsTypeStyle(plan.withdrawalRule);
    const isClosed = plan.status === 'closed';
    const daysLeft = daysUntil(plan.maturityDate);

    return (
        <Link
            href={show(plan.id)}
            className={cn(
                'group flex h-full flex-col rounded-landing-lg border border-surface-200 bg-white p-4 shadow-landing-sm transition-colors hover:border-brand/40 focus-visible:ring-2 focus-visible:ring-highlight focus-visible:outline-none',
                isClosed && 'opacity-75',
            )}
        >
            <div className="flex items-start gap-3">
                <span
                    className={cn(
                        'flex size-10 shrink-0 items-center justify-center rounded-landing',
                        style.tone,
                    )}
                >
                    <style.icon className="size-5" />
                </span>
                <div className="min-w-0 flex-1">
                    <p className="truncate font-semibold text-ink">
                        {plan.name}
                    </p>
                    <p className="text-xs text-ink-400">{plan.typeLabel}</p>
                </div>
                {isClosed ? (
                    <StatusBadge tone="neutral">Closed</StatusBadge>
                ) : plan.progress >= 100 ? (
                    <StatusBadge tone="success">Target reached</StatusBadge>
                ) : (
                    plan.autoDebit && (
                        <StatusBadge tone="info">Auto-save</StatusBadge>
                    )
                )}
            </div>

            <p className="mt-3 font-display text-xl font-semibold text-ink tabular-nums">
                {formatNaira(plan.balance)}
                <span className="ml-1.5 font-body text-xs font-medium text-ink-400">
                    of {formatNaira(plan.targetAmount)}
                </span>
            </p>
            <div className="mt-2 flex items-center gap-2">
                <div className="flex-1">
                    <ProgressBar
                        value={plan.progress}
                        label={`${plan.name} progress`}
                    />
                </div>
                <span className="text-xs font-semibold text-ink-500 tabular-nums">
                    {plan.progress}%
                </span>
            </div>

            <dl className="mt-3 grid grid-cols-2 gap-2 border-t border-surface-100 pt-3 text-xs">
                <div className="min-w-0">
                    <dt className="flex items-center gap-1 text-ink-400">
                        <Repeat className="size-3" />
                        Saves
                    </dt>
                    <dd className="mt-0.5 truncate font-semibold text-ink-700">
                        {formatNaira(plan.contributionAmount)}{' '}
                        {plan.frequencyLabel.toLowerCase()}
                    </dd>
                </div>
                <div className="min-w-0">
                    <dt className="flex items-center gap-1 text-ink-400">
                        <CalendarClock className="size-3" />
                        {!isClosed && plan.nextDebitOn ? 'Next' : 'Matures'}
                    </dt>
                    <dd className="mt-0.5 truncate font-semibold text-ink-700">
                        {!isClosed && plan.nextDebitOn
                            ? formatDate(plan.nextDebitOn)
                            : formatDate(plan.maturityDate)}
                        {!isClosed && !plan.nextDebitOn && daysLeft > 0 && (
                            <span className="font-normal text-ink-400">
                                {' '}
                                · {daysLeft}d
                            </span>
                        )}
                    </dd>
                </div>
            </dl>

            <span className="mt-3 inline-flex items-center gap-1 text-sm font-semibold text-brand group-hover:text-highlight-dark">
                {isClosed ? 'View history' : 'Manage plan'}
                <ArrowRight className="size-3.5" />
            </span>
        </Link>
    );
}

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