import AdminLayout from '@/Layouts/AdminLayout';
import { DataTable, type TableMeta } from '@/components/admin/DataTable';
import PageHeader from '@/components/admin/PageHeader';
import PlanBadge from '@/components/admin/PlanBadge';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useDataTable, type TableParams } from '@/hooks/useDataTable';
import { api } from '@/lib/api';
import { parseServerDate } from '@/lib/date';
import { Head, Link } from '@inertiajs/react';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import type { ColumnDef } from '@tanstack/react-table';
import { format } from 'date-fns';
import { Download, Eye, MoreHorizontal } from 'lucide-react';

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

interface Subscription {
    id: string;
    tenant_id: string;
    tenant_name: string;
    plan_slug: string;
    plan_name: string;
    status: string;
    billing_cycle: string;
    mrr_raw: number;
    mrr: string;
    trial_ends_at: string | null;
    current_period_start: string | null;
    current_period_end: string | null;
    suspended_at: string | null;
    canceled_at: string | null;
    created_at: string;
}

interface SubscriptionsResponse {
    data: Subscription[];
    meta: TableMeta;
    filter_counts: Record<string, number>;
}

// ── Status label / colour ─────────────────────────────────────────────────────

const STATUS_MAP: Record<string, { label: string; className: string }> = {
    trialing: {
        label: 'Trial',
        className:
            'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
    },
    active: {
        label: 'Active',
        className:
            'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
    },
    past_due: {
        label: 'Past Due',
        className:
            'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
    },
    suspended: {
        label: 'Suspended',
        className:
            'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
    },
    canceled: {
        label: 'Canceled',
        className: 'bg-muted text-muted-foreground',
    },
};

function SubStatusBadge({ status }: { status: string }) {
    const s = STATUS_MAP[status] ?? {
        label: status,
        className: 'bg-muted text-muted-foreground',
    };
    return (
        <span
            className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${s.className}`}
        >
            {s.label}
        </span>
    );
}

// ── Billing cycle badge ───────────────────────────────────────────────────────

function CycleBadge({ cycle }: { cycle: string }) {
    return (
        <span className="text-muted-foreground bg-muted inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium capitalize">
            {cycle}
        </span>
    );
}

// ── Quick filter chips ────────────────────────────────────────────────────────

const FILTER_DEFS = [
    { value: 'all', label: 'All' },
    { value: 'trialing', label: 'Trial' },
    { value: 'active', label: 'Active' },
    { value: 'past_due', label: 'Past Due' },
    { value: 'suspended', label: 'Suspended' },
    { value: 'canceled', label: 'Canceled' },
];

// ── API fetch ─────────────────────────────────────────────────────────────────

function fetchSubscriptions(
    params: TableParams,
): Promise<SubscriptionsResponse> {
    const sp = new URLSearchParams({ page: String(params.page) });
    if (params.filter && params.filter !== 'all')
        sp.set('filter', params.filter);
    if (params.sort) sp.set('sort', params.sort);
    if (params.dir !== 'asc') sp.set('dir', params.dir);
    if (params.search) sp.set('search', params.search);
    return api.get(`/admin/api/subscriptions?${sp}`);
}

// ── Row actions ───────────────────────────────────────────────────────────────

function RowActions({ sub }: { sub: Subscription }) {
    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <button className="text-muted-foreground hover:bg-muted/60 hover:text-foreground flex h-7 w-7 items-center justify-center rounded-md transition-colors focus:outline-none">
                    <MoreHorizontal className="h-4 w-4" />
                    <span className="sr-only">
                        Actions for {sub.tenant_name}
                    </span>
                </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-44">
                <DropdownMenuItem asChild className="gap-2 text-xs">
                    <Link href={`/admin/tenants/${sub.tenant_id}`}>
                        <Eye className="h-3.5 w-3.5" />
                        View tenant
                    </Link>
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    );
}

// ── Column definitions ────────────────────────────────────────────────────────

const columns: ColumnDef<Subscription, unknown>[] = [
    {
        accessorKey: 'tenant_name',
        header: 'Tenant',
        meta: { sortable: true, label: 'Tenant' },
        cell: ({ row }) => (
            <Link
                href={`/admin/tenants/${row.original.tenant_id}`}
                className="block min-w-0 hover:opacity-80"
            >
                <p className="text-foreground truncate font-medium">
                    {row.original.tenant_name}
                </p>
                <p className="text-muted-foreground truncate text-[11px]">
                    {row.original.tenant_id}
                </p>
            </Link>
        ),
    },
    {
        accessorKey: 'plan_name',
        header: 'Plan',
        meta: { sortable: true, label: 'Plan' },
        cell: ({ row }) => <PlanBadge plan={row.original.plan_name} />,
    },
    {
        accessorKey: 'status',
        header: 'Status',
        meta: { sortable: true, label: 'Status' },
        cell: ({ row }) => <SubStatusBadge status={row.original.status} />,
    },
    {
        accessorKey: 'billing_cycle',
        header: 'Cycle',
        meta: { sortable: true, label: 'Cycle' },
        cell: ({ row }) => <CycleBadge cycle={row.original.billing_cycle} />,
    },
    {
        accessorKey: 'mrr',
        header: 'MRR',
        meta: { sortable: true, sortKey: 'mrr_raw', label: 'MRR' },
        cell: ({ row }) => (
            <span className="text-foreground/90 font-medium tabular-nums">
                {row.original.mrr}
            </span>
        ),
    },
    {
        accessorKey: 'trial_ends_at',
        header: 'Trial / Period end',
        meta: { sortable: true, label: 'Trial / Period end' },
        cell: ({ row }) => {
            const trial = row.original.trial_ends_at;
            const periodEnd = row.original.current_period_end;
            const date = trial ?? periodEnd;
            const label = trial ? 'Trial' : 'Period';
            return date ? (
                <div>
                    <p className="text-muted-foreground text-[10px]">{label}</p>
                    <p className="text-foreground/80 text-xs tabular-nums">
                        {format(parseServerDate(date), 'dd MMM yyyy')}
                    </p>
                </div>
            ) : (
                <span className="text-muted-foreground text-xs">—</span>
            );
        },
    },
    {
        accessorKey: 'created_at',
        header: 'Started',
        meta: { sortable: true, label: 'Started' },
        cell: ({ row }) => (
            <span className="text-muted-foreground text-xs tabular-nums">
                {format(
                    parseServerDate(row.original.created_at),
                    'dd MMM yyyy',
                )}
            </span>
        ),
    },
    {
        id: '_actions',
        header: '',
        cell: ({ row }) => <RowActions sub={row.original} />,
        enableHiding: false,
    },
];

// ── Empty meta placeholder ────────────────────────────────────────────────────

const EMPTY_META: TableMeta = {
    current_page: 1,
    last_page: 1,
    total: 0,
    per_page: 25,
    from: 0,
    to: 0,
};

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

export default function SubscriptionsIndex() {
    const { params, setParams } = useDataTable({
        sort: 'created_at',
        dir: 'desc',
    });

    const { data, isLoading, isFetching } = useQuery({
        queryKey: ['admin.subscriptions', params],
        queryFn: () => fetchSubscriptions(params),
        placeholderData: keepPreviousData,
    });

    const filterCounts = data?.filter_counts ?? {};

    const quickFilters = FILTER_DEFS.map((f) => ({
        ...f,
        count: filterCounts[f.value] ?? 0,
    }));

    return (
        <AdminLayout title="Subscriptions">
            <Head title="Subscriptions" />

            <div className="space-y-6 p-6 lg:p-8">
                <PageHeader
                    title="Subscriptions"
                    description="All tenant subscriptions across every plan"
                />

                <DataTable
                    columns={columns}
                    data={data?.data ?? []}
                    meta={data?.meta ?? EMPTY_META}
                    params={params}
                    isLoading={isLoading}
                    isFetching={isFetching}
                    onParamsChange={setParams}
                    quickFilters={quickFilters}
                    bulkActions={[
                        {
                            label: 'Export CSV',
                            icon: Download,
                            onClick: (rows) => {
                                const csv = [
                                    'Tenant,Plan,Status,Cycle,MRR,Trial/Period End,Started',
                                ]
                                    .concat(
                                        rows.map(
                                            (r) =>
                                                `${r.tenant_name},${r.plan_name},${r.status},${r.billing_cycle},${r.mrr},${r.trial_ends_at ?? r.current_period_end ?? ''},${r.created_at}`,
                                        ),
                                    )
                                    .join('\n');
                                const a = document.createElement('a');
                                a.href =
                                    'data:text/csv,' + encodeURIComponent(csv);
                                a.download = 'subscriptions.csv';
                                a.click();
                            },
                        },
                    ]}
                    searchPlaceholder="Search by tenant or plan…"
                    noun="subscriptions"
                    getRowId={(row) => String(row.id)}
                />
            </div>
        </AdminLayout>
    );
}
