import { useCurrency } from '@/hooks/useCurrency';
import ClientLayout from '@/Layouts/ClientLayout';
import { parseServerDate } from '@/lib/date';
import { AppDetail, AppPlan, AppSubscription, PageProps } from '@/types';
import { Head, useForm } from '@inertiajs/react';
import { CheckCircle2, CreditCard, Sparkles, Zap } from 'lucide-react';
import { useState } from 'react';
import AppNav from './components/AppNav';

type Props = PageProps<{
    app: AppDetail;
    plans: AppPlan[];
    subscription: AppSubscription | null;
}>;

function statusLabel(status: string): string {
    const map: Record<string, string> = {
        trialing: 'Trial',
        active: 'Active',
        past_due: 'Past due',
        suspended: 'Suspended',
        canceled: 'Canceled',
    };
    return map[status] ?? status;
}

function statusColor(status: string): string {
    switch (status) {
        case 'trialing':
            return 'text-sky-600 bg-sky-50 border-sky-200 dark:text-sky-400 dark:bg-sky-900/20 dark:border-sky-700/30';
        case 'active':
            return 'text-emerald-600 bg-emerald-50 border-emerald-200 dark:text-emerald-400 dark:bg-emerald-900/20 dark:border-emerald-700/30';
        case 'past_due':
            return 'text-amber-600 bg-amber-50 border-amber-200 dark:text-amber-400 dark:bg-amber-900/20 dark:border-amber-700/30';
        default:
            return 'text-red-600 bg-red-50 border-red-200 dark:text-red-400 dark:bg-red-900/20 dark:border-red-700/30';
    }
}

const LIMIT_LABELS: [string, keyof NonNullable<AppPlan['limits']>][] = [
    ['Branches', 'maxBranches'],
    ['Staff users', 'maxStaffUsers'],
    ['Active borrowers', 'maxActiveBorrowers'],
    ['Active loans', 'maxActiveLoans'],
];

export default function Billing({ app, plans, subscription }: Props) {
    const [cycle, setCycle] = useState<'monthly' | 'yearly'>(
        (subscription?.billingCycle as 'monthly' | 'yearly') ?? 'monthly',
    );
    const { format } = useCurrency();

    function formatPrice(plan: AppPlan, c: 'monthly' | 'yearly'): string {
        const num = c === 'yearly' ? plan.priceYearly : plan.priceMonthly;
        if (num === 0) return 'Free';
        return `${format(num)}/${c === 'yearly' ? 'yr' : 'mo'}`;
    }

    const { data, setData, post, processing } = useForm({
        plan_id: subscription?.planId ?? plans[0]?.id ?? 0,
        billing_cycle: cycle,
    });

    const currentPlanId = subscription?.planId;
    const isChanging =
        data.plan_id !== currentPlanId ||
        data.billing_cycle !== subscription?.billingCycle;

    function submit(e: React.FormEvent) {
        e.preventDefault();
        post(route('app.billing.update', { tenant: app.id }));
    }

    const trialDaysLeft = subscription?.trialEndsAt
        ? Math.max(
              0,
              Math.ceil(
                  (new Date(subscription.trialEndsAt).getTime() - Date.now()) /
                      86_400_000,
              ),
          )
        : null;

    return (
        <ClientLayout title={`${app.name} — Billing`}>
            <Head title={`${app.name} — Billing`} />

            <AppNav app={app} />

            <div className="space-y-6 p-6 lg:p-8">
                {/* Current subscription summary */}
                {subscription && (
                    <div className="pf-glass divide-border grid grid-cols-1 divide-y sm:grid-cols-3 sm:divide-x sm:divide-y-0">
                        <div className="px-5 py-4">
                            <p className="text-muted-foreground dark:text-muted-foreground/70 mb-1 text-xs">
                                Current plan
                            </p>
                            <div className="flex items-center gap-2">
                                <p className="text-foreground font-semibold">
                                    {subscription.planName ?? '—'}
                                </p>
                                <span
                                    className={`rounded-full border px-2 py-0.5 text-[10px] font-semibold ${statusColor(subscription.status)}`}
                                >
                                    {statusLabel(subscription.status)}
                                </span>
                            </div>
                        </div>
                        <div className="px-5 py-4">
                            <p className="text-muted-foreground dark:text-muted-foreground/70 mb-1 text-xs">
                                Billing cycle
                            </p>
                            <p className="text-foreground font-semibold capitalize">
                                {subscription.billingCycle}
                            </p>
                        </div>
                        <div className="px-5 py-4">
                            <p className="text-muted-foreground dark:text-muted-foreground/70 mb-1 text-xs">
                                {subscription.status === 'trialing'
                                    ? 'Trial ends'
                                    : 'Next renewal'}
                            </p>
                            <div className="flex items-center gap-2">
                                <p className="text-foreground font-semibold">
                                    {subscription.status === 'trialing' &&
                                    subscription.trialEndsAt
                                        ? parseServerDate(
                                              subscription.trialEndsAt,
                                          ).toLocaleDateString()
                                        : subscription.currentPeriodEnd
                                          ? parseServerDate(
                                                subscription.currentPeriodEnd,
                                            ).toLocaleDateString()
                                          : '—'}
                                </p>
                                {subscription.status === 'trialing' &&
                                    trialDaysLeft !== null && (
                                        <span className="rounded-full border border-sky-200 bg-sky-50 px-2 py-0.5 text-[10px] font-semibold text-sky-700 dark:border-sky-700/30 dark:bg-sky-900/20 dark:text-sky-400">
                                            {trialDaysLeft}d left
                                        </span>
                                    )}
                            </div>
                        </div>
                    </div>
                )}

                {/* Plan selector */}
                <form onSubmit={submit} className="space-y-5">
                    <div className="flex items-center justify-between gap-4">
                        <h2 className="text-foreground text-sm font-semibold">
                            {subscription ? 'Change plan' : 'Select a plan'}
                        </h2>

                        {/* Billing cycle toggle */}
                        <div className="bg-muted/40 border-border inline-flex rounded-xl border p-1">
                            {(['monthly', 'yearly'] as const).map((c) => (
                                <button
                                    key={c}
                                    type="button"
                                    onClick={() => {
                                        setCycle(c);
                                        setData('billing_cycle', c);
                                    }}
                                    className={`rounded-lg px-4 py-1.5 text-sm font-medium transition-all ${
                                        cycle === c
                                            ? 'bg-background text-foreground shadow-sm'
                                            : 'text-muted-foreground hover:text-foreground'
                                    }`}
                                >
                                    {c === 'monthly' ? 'Monthly' : 'Yearly'}
                                    {c === 'yearly' && (
                                        <span className="text-primary ml-1.5 text-[10px] font-bold">
                                            SAVE 20%
                                        </span>
                                    )}
                                </button>
                            ))}
                        </div>
                    </div>

                    {plans.length === 0 ? (
                        <div className="py-16 text-center">
                            <Sparkles className="text-muted-foreground dark:text-muted-foreground/40 mx-auto mb-3 h-8 w-8" />
                            <p className="text-muted-foreground text-sm">
                                No plans available. Contact support.
                            </p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
                            {plans.map((plan) => {
                                const selected = data.plan_id === plan.id;
                                const isCurrent = plan.id === currentPlanId;

                                return (
                                    <button
                                        key={plan.id}
                                        type="button"
                                        onClick={() =>
                                            setData('plan_id', plan.id)
                                        }
                                        className={`relative flex flex-col rounded-xl border p-5 text-left transition-all ${
                                            selected
                                                ? 'border-primary bg-primary/5 ring-primary/30 ring-2'
                                                : 'border-border hover:border-primary/40 hover:bg-muted/20'
                                        }`}
                                    >
                                        {isCurrent && (
                                            <span className="absolute top-3 right-3 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[9px] font-bold text-emerald-700 dark:border-emerald-700/30 dark:bg-emerald-900/20 dark:text-emerald-400">
                                                Current
                                            </span>
                                        )}
                                        {selected && !isCurrent && (
                                            <CheckCircle2 className="text-primary absolute top-3 right-3 h-4 w-4" />
                                        )}

                                        <div className="mb-1 flex items-center gap-1.5">
                                            <Zap className="text-primary h-3.5 w-3.5" />
                                            <p className="text-foreground text-sm font-semibold">
                                                {plan.name}
                                            </p>
                                        </div>
                                        <p className="text-primary mb-3 text-xl font-bold">
                                            {formatPrice(plan, cycle)}
                                        </p>
                                        {plan.description && (
                                            <p className="text-muted-foreground mb-4 text-xs leading-relaxed">
                                                {plan.description}
                                            </p>
                                        )}

                                        {/* Limits list */}
                                        {plan.limits && (
                                            <ul className="mt-auto space-y-1.5">
                                                {LIMIT_LABELS.map(
                                                    ([label, key]) => {
                                                        const val =
                                                            plan.limits![key];
                                                        return (
                                                            <li
                                                                key={key}
                                                                className="flex items-center gap-1.5 text-xs"
                                                            >
                                                                <CreditCard className="text-muted-foreground dark:text-muted-foreground/40 h-3 w-3 shrink-0" />
                                                                <span className="text-muted-foreground">
                                                                    {label}:
                                                                </span>
                                                                <span className="text-foreground font-medium">
                                                                    {val == null
                                                                        ? '∞'
                                                                        : val.toLocaleString()}
                                                                </span>
                                                            </li>
                                                        );
                                                    },
                                                )}
                                            </ul>
                                        )}

                                        {(plan.trialDays ?? 0) > 0 &&
                                            !subscription && (
                                                <p className="text-primary mt-3 text-xs font-medium">
                                                    {plan.trialDays}-day free
                                                    trial
                                                </p>
                                            )}
                                    </button>
                                );
                            })}
                        </div>
                    )}

                    {plans.length > 0 && isChanging && (
                        <div className="flex items-center justify-end gap-3 pt-2">
                            <button
                                type="button"
                                onClick={() => {
                                    const resetCycle =
                                        (subscription?.billingCycle ??
                                            'monthly') as 'monthly' | 'yearly';
                                    setData(
                                        'plan_id',
                                        currentPlanId ?? plans[0]?.id ?? 0,
                                    );
                                    setData('billing_cycle', resetCycle);
                                    setCycle(resetCycle);
                                }}
                                className="border-border bg-secondary/40 text-foreground rounded-xl border px-4 py-2.5 text-sm font-medium"
                            >
                                Cancel
                            </button>
                            <button
                                type="submit"
                                disabled={processing}
                                className="pf-btn px-6 py-2.5 text-sm disabled:cursor-not-allowed disabled:opacity-50"
                            >
                                {processing
                                    ? 'Updating…'
                                    : 'Confirm plan change'}
                            </button>
                        </div>
                    )}
                </form>
            </div>
        </ClientLayout>
    );
}
