import AdminLayout from '@/Layouts/AdminLayout';
import PageHeader from '@/components/admin/PageHeader';
import { useCurrency } from '@/hooks/useCurrency';
import { api } from '@/lib/api';
import { cn } from '@/lib/utils';
import { Head, Link } from '@inertiajs/react';
import {
    BarChart3,
    Building2,
    Check,
    CreditCard,
    Eye,
    EyeOff,
    Layers,
    MoreHorizontal,
    Pencil,
    Plus,
    RefreshCw,
    Trash2,
    Users,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';

// ── Types ─────────────────────────────────────────────────────────────────────

interface PlanLimits {
    max_branches: number | null;
    max_staff_users: number | null;
    max_active_borrowers: number | null;
    max_active_loans: number | null;
    max_loan_products: number | null;
    max_savings_products: number | null;
    max_api_calls_daily: number | null;
    max_sms_per_month: number | null;
    max_storage_gb: number | null;
}

interface Plan {
    id: string;
    slug: string;
    name: string;
    description: string | null;
    price_monthly: number;
    price_yearly: number;
    currency: string;
    is_active: boolean;
    is_public: boolean;
    trial_days: number;
    sort_order: number;
    deleted_at: string | null;
    subscriptions_count: number;
    limits: Partial<PlanLimits>;
    sub_module_slugs: string[];
}

interface Props {
    plans: Plan[];
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function fmt(val: number | null | undefined, unit: string): string {
    if (val == null) return `Unlimited ${unit}`;
    return `${val.toLocaleString()} ${unit}`;
}

function PlanCard({
    plan,
    onToggle,
    onDelete,
    onRestore,
}: {
    plan: Plan;
    onToggle: (id: string) => void;
    onDelete: (id: string) => void;
    onRestore: (id: string) => void;
}) {
    const [menuOpen, setMenuOpen] = useState(false);
    const { formatBase } = useCurrency();
    const isArchived = !!plan.deleted_at;

    const tierColor: Record<string, string> = {
        trial: 'from-purple-500/10 to-purple-500/5 border-purple-500/20',
        starter: 'from-blue-500/10 to-blue-500/5 border-blue-500/20',
        professional:
            'from-emerald-500/10 to-emerald-500/5 border-emerald-500/20',
        enterprise: 'from-amber-500/10 to-amber-500/5 border-amber-500/20',
    };

    const badgeColor: Record<string, string> = {
        trial: 'bg-purple-500/10 text-purple-600 dark:text-purple-400',
        starter: 'bg-blue-500/10 text-blue-600 dark:text-blue-400',
        professional:
            'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',
        enterprise: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',
    };

    const cardGradient =
        tierColor[plan.slug] ?? 'from-muted/10 to-muted/5 border-border';
    const badge = badgeColor[plan.slug] ?? 'bg-muted text-muted-foreground';

    return (
        <div
            className={cn(
                'pf-glass relative flex flex-col gap-4 rounded-2xl border bg-gradient-to-br p-6 transition-all',
                cardGradient,
                isArchived && 'opacity-60',
            )}
        >
            {/* Header */}
            <div className="flex items-start justify-between gap-3">
                <div className="min-w-0 flex-1">
                    <div className="mb-1 flex flex-wrap items-center gap-2">
                        <span
                            className={cn(
                                'rounded-full px-2.5 py-0.5 text-xs font-semibold',
                                badge,
                            )}
                        >
                            {plan.name}
                        </span>
                        {!plan.is_active && (
                            <span className="bg-destructive/10 text-destructive rounded-full px-2 py-0.5 text-xs font-semibold">
                                Inactive
                            </span>
                        )}
                        {isArchived && (
                            <span className="bg-muted text-muted-foreground rounded-full px-2 py-0.5 text-xs font-semibold">
                                Archived
                            </span>
                        )}
                        {plan.trial_days > 0 && (
                            <span className="rounded-full bg-purple-500/10 px-2 py-0.5 text-xs font-semibold text-purple-600 dark:text-purple-400">
                                {plan.trial_days}d trial
                            </span>
                        )}
                    </div>
                    {plan.description && (
                        <p className="text-muted-foreground line-clamp-2 text-xs">
                            {plan.description}
                        </p>
                    )}
                </div>

                {/* Actions menu */}
                <div className="relative shrink-0">
                    <button
                        onClick={() => setMenuOpen((o) => !o)}
                        className="border-border text-muted-foreground hover:bg-muted/60 hover:text-foreground flex h-7 w-7 items-center justify-center rounded-lg border transition-colors"
                    >
                        <MoreHorizontal className="h-4 w-4" />
                    </button>
                    {menuOpen && (
                        <>
                            <div
                                className="fixed inset-0 z-10"
                                onClick={() => setMenuOpen(false)}
                            />
                            <div className="border-border bg-popover absolute top-8 right-0 z-20 min-w-[160px] rounded-xl border py-1 shadow-lg">
                                {!isArchived && (
                                    <Link
                                        href={`/admin/plans/${plan.id}/edit`}
                                        className="text-foreground hover:bg-muted/60 flex items-center gap-2.5 px-3 py-2 text-sm"
                                        onClick={() => setMenuOpen(false)}
                                    >
                                        <Pencil className="h-3.5 w-3.5" /> Edit
                                    </Link>
                                )}
                                {!isArchived && (
                                    <button
                                        onClick={() => {
                                            onToggle(plan.id);
                                            setMenuOpen(false);
                                        }}
                                        className="text-foreground hover:bg-muted/60 flex w-full items-center gap-2.5 px-3 py-2 text-sm"
                                    >
                                        {plan.is_active ? (
                                            <>
                                                <EyeOff className="h-3.5 w-3.5" />{' '}
                                                Deactivate
                                            </>
                                        ) : (
                                            <>
                                                <Eye className="h-3.5 w-3.5" />{' '}
                                                Activate
                                            </>
                                        )}
                                    </button>
                                )}
                                {!isArchived && (
                                    <button
                                        onClick={() => {
                                            onDelete(plan.id);
                                            setMenuOpen(false);
                                        }}
                                        className="text-destructive hover:bg-destructive/10 flex w-full items-center gap-2.5 px-3 py-2 text-sm"
                                    >
                                        <Trash2 className="h-3.5 w-3.5" />{' '}
                                        Archive
                                    </button>
                                )}
                                {isArchived && (
                                    <button
                                        onClick={() => {
                                            onRestore(plan.id);
                                            setMenuOpen(false);
                                        }}
                                        className="text-foreground hover:bg-muted/60 flex w-full items-center gap-2.5 px-3 py-2 text-sm"
                                    >
                                        <RefreshCw className="h-3.5 w-3.5" />{' '}
                                        Restore
                                    </button>
                                )}
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* Pricing */}
            <div className="flex items-end gap-1">
                <span className="text-foreground text-3xl font-bold tabular-nums">
                    {plan.price_monthly === 0
                        ? 'Free'
                        : formatBase(plan.price_monthly)}
                </span>
                {plan.price_monthly > 0 && (
                    <span className="text-muted-foreground mb-1 text-sm">
                        /mo
                    </span>
                )}
                {plan.price_yearly > 0 && (
                    <span className="text-muted-foreground mb-1 ml-2 text-xs">
                        · {formatBase(plan.price_yearly)}/yr
                    </span>
                )}
            </div>

            {/* Key limits */}
            <div className="grid grid-cols-2 gap-2">
                <LimitChip
                    icon={Building2}
                    label={fmt(plan.limits.max_branches, 'branches')}
                />
                <LimitChip
                    icon={Users}
                    label={fmt(plan.limits.max_staff_users, 'users')}
                />
                <LimitChip
                    icon={CreditCard}
                    label={fmt(plan.limits.max_active_loans, 'loans')}
                />
                <LimitChip
                    icon={BarChart3}
                    label={fmt(plan.limits.max_active_borrowers, 'borrowers')}
                />
            </div>

            {/* Module count + subscriber count */}
            <div className="border-border flex items-center justify-between border-t pt-3">
                <div className="flex items-center gap-1.5">
                    <Layers className="text-muted-foreground h-3.5 w-3.5" />
                    <span className="text-muted-foreground text-xs">
                        {plan.sub_module_slugs.length} sub-modules
                    </span>
                </div>
                <div className="flex items-center gap-1.5">
                    <Check className="text-muted-foreground h-3.5 w-3.5" />
                    <span className="text-muted-foreground text-xs">
                        {plan.subscriptions_count} tenants
                    </span>
                </div>
            </div>
        </div>
    );
}

function LimitChip({
    icon: Icon,
    label,
}: {
    icon: React.ComponentType<{ className?: string }>;
    label: string;
}) {
    return (
        <div className="bg-background/40 flex items-center gap-1.5 rounded-lg px-2.5 py-1.5">
            <Icon className="text-muted-foreground h-3 w-3 shrink-0" />
            <span className="text-foreground truncate text-xs">{label}</span>
        </div>
    );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export default function PlansIndex({ plans: initialPlans }: Props) {
    const [plans, setPlans] = useState(initialPlans);

    const handleToggle = async (id: string) => {
        try {
            const res = await api.patch<{ is_active: boolean }>(
                `/admin/plans/${id}/toggle-active`,
            );
            setPlans((prev) =>
                prev.map((p) =>
                    p.id === id ? { ...p, is_active: res.is_active } : p,
                ),
            );
            toast.success('Plan status updated');
        } catch {
            toast.error('Failed to update plan status');
        }
    };

    const handleDelete = async (id: string) => {
        try {
            await api.delete(`/admin/plans/${id}`);
            setPlans((prev) =>
                prev.map((p) =>
                    p.id === id
                        ? { ...p, deleted_at: new Date().toISOString() }
                        : p,
                ),
            );
            toast.success('Plan archived');
        } catch {
            toast.error('Failed to archive plan');
        }
    };

    const handleRestore = async (id: string) => {
        try {
            await api.post(`/admin/plans/${id}/restore`);
            setPlans((prev) =>
                prev.map((p) => (p.id === id ? { ...p, deleted_at: null } : p)),
            );
            toast.success('Plan restored');
        } catch {
            toast.error('Failed to restore plan');
        }
    };

    const active = plans.filter((p) => !p.deleted_at);
    const archived = plans.filter((p) => p.deleted_at);

    return (
        <AdminLayout
            title="Plans"
            breadcrumbs={[{ label: 'Billing' }, { label: 'Plans' }]}
        >
            <Head title="Plans" />

            <div className="space-y-8 p-6 lg:p-8">
                <PageHeader
                    title="Subscription Plans"
                    description="Define pricing tiers, feature access, and usage limits for tenants."
                    action={
                        <Link
                            href="/admin/plans/create"
                            className="pf-btn pf-btn-primary flex items-center gap-2"
                        >
                            <Plus className="h-4 w-4" />
                            New Plan
                        </Link>
                    }
                />

                {/* Active plans */}
                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-4">
                    {active.map((plan) => (
                        <PlanCard
                            key={plan.id}
                            plan={plan}
                            onToggle={handleToggle}
                            onDelete={handleDelete}
                            onRestore={handleRestore}
                        />
                    ))}
                    {active.length === 0 && (
                        <div className="pf-glass col-span-full flex flex-col items-center gap-3 rounded-2xl p-12 text-center">
                            <Layers className="text-muted-foreground dark:text-muted-foreground/40 h-10 w-10" />
                            <p className="text-muted-foreground text-sm">
                                No active plans. Create your first plan.
                            </p>
                        </div>
                    )}
                </div>

                {/* Archived */}
                {archived.length > 0 && (
                    <div>
                        <h3 className="text-muted-foreground mb-4 text-xs font-semibold tracking-widest uppercase">
                            Archived Plans
                        </h3>
                        <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-4">
                            {archived.map((plan) => (
                                <PlanCard
                                    key={plan.id}
                                    plan={plan}
                                    onToggle={handleToggle}
                                    onDelete={handleDelete}
                                    onRestore={handleRestore}
                                />
                            ))}
                        </div>
                    </div>
                )}
            </div>
        </AdminLayout>
    );
}
