import { getChartTheme } from '@/components/admin/chart-theme';
import StatCard from '@/components/admin/StatCard';
import { useIsDark } from '@/hooks/useIsDark';
import { Activity, Globe, TrendingUp, Users } from 'lucide-react';
import {
    Bar,
    BarChart,
    CartesianGrid,
    Cell,
    Legend,
    Pie,
    PieChart,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis,
} from 'recharts';
import { ChartCard, HBar, Section } from './shared';
import type { Cohort, TenantMetrics } from './types';

function CohortTable({ cohorts }: { cohorts: Cohort[] }) {
    if (cohorts.length === 0) {
        return (
            <p className="text-muted-foreground py-8 text-center text-xs">
                No cohort data yet
            </p>
        );
    }

    const maxMonths = Math.max(...cohorts.map((c) => c.retention.length));

    return (
        <div className="overflow-x-auto">
            <table className="w-full border-separate border-spacing-0.5 text-xs">
                <thead>
                    <tr className="text-muted-foreground">
                        <th className="px-2 py-1 text-left font-medium">
                            Cohort
                        </th>
                        <th className="px-2 py-1 text-right font-medium">
                            Size
                        </th>
                        {Array.from({ length: maxMonths }, (_, k) => (
                            <th
                                key={k}
                                className="px-2 py-1 text-center font-medium"
                            >
                                M{k}
                            </th>
                        ))}
                    </tr>
                </thead>
                <tbody>
                    {cohorts.map((c) => (
                        <tr key={c.month}>
                            <td className="text-foreground px-2 py-1 whitespace-nowrap">
                                {c.month}
                            </td>
                            <td className="text-muted-foreground px-2 py-1 text-right tabular-nums">
                                {c.size}
                            </td>
                            {Array.from({ length: maxMonths }, (_, k) => {
                                const pct = c.retention[k];
                                if (pct === undefined) {
                                    return <td key={k} />;
                                }
                                return (
                                    <td
                                        key={k}
                                        className="text-foreground rounded-sm px-2 py-1 text-center tabular-nums"
                                        style={{
                                            backgroundColor: `hsl(17 92% 58% / ${(pct / 100) * 0.55 + (pct > 0 ? 0.08 : 0)})`,
                                        }}
                                    >
                                        {pct}%
                                    </td>
                                );
                            })}
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

export default function TenantsSection({
    tenants,
    cohorts,
    days,
}: {
    tenants: TenantMetrics;
    cohorts: Cohort[];
    days: number;
}) {
    const isDark = useIsDark();
    const ct = getChartTheme(isDark);
    const maxCountry = Math.max(...tenants.countries.map((c) => c.count), 1);

    return (
        <Section title="Tenants" icon={Users}>
            {/* KPI row */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                <StatCard
                    label="Total Tenants"
                    value={tenants.total.toLocaleString()}
                    sub={`${tenants.new_in_window} new in last ${days} days`}
                    icon={Globe}
                    iconColor="bg-sky-400/25 text-sky-600 dark:bg-sky-400/15 dark:text-sky-400"
                    trend={
                        tenants.growth_pct !== null
                            ? `${Math.abs(tenants.growth_pct)}%`
                            : undefined
                    }
                    positive={(tenants.growth_pct ?? 0) >= 0}
                />
                <StatCard
                    label={`New (${days} days)`}
                    value={tenants.new_in_window.toLocaleString()}
                    sub={`Vs previous ${days} days`}
                    icon={TrendingUp}
                    iconColor="bg-emerald-400/25 text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400"
                />
                <StatCard
                    label={`Churn (${days} days)`}
                    value={tenants.churn_count.toLocaleString()}
                    sub={
                        tenants.churned_mrr
                            ? `Rate: ${tenants.churn_rate} · ${tenants.churned_mrr} MRR lost`
                            : `Rate: ${tenants.churn_rate}`
                    }
                    icon={Activity}
                    iconColor="bg-red-400/25 text-red-600 dark:bg-red-400/15 dark:text-red-400"
                    trend={tenants.churn_rate}
                    positive={false}
                />
                <StatCard
                    label="Countries"
                    value={tenants.countries.length.toLocaleString()}
                    sub="Unique markets"
                    icon={Globe}
                    iconColor="bg-violet-400/25 text-violet-600 dark:bg-violet-400/15 dark:text-violet-400"
                />
            </div>

            <div className="grid gap-4 lg:grid-cols-3">
                {/* Signup trend */}
                <ChartCard title="Tenant Signups" sub="New tenants per month">
                    <ResponsiveContainer width="100%" height={180}>
                        <BarChart
                            data={tenants.signup_trend}
                            margin={{ top: 4, right: 4, bottom: 0, left: -12 }}
                        >
                            <CartesianGrid
                                strokeDasharray="3 3"
                                stroke={ct.grid}
                                vertical={false}
                            />
                            <XAxis
                                dataKey="month"
                                tick={ct.tick}
                                axisLine={false}
                                tickLine={false}
                            />
                            <YAxis
                                tick={ct.tick}
                                axisLine={false}
                                tickLine={false}
                                allowDecimals={false}
                            />
                            <Tooltip
                                contentStyle={ct.tooltip.contentStyle}
                                cursor={ct.tooltip.cursor}
                            />
                            <Bar
                                dataKey="signups"
                                fill="#3B82F6"
                                radius={[3, 3, 0, 0]}
                            />
                        </BarChart>
                    </ResponsiveContainer>
                </ChartCard>

                {/* Status donut */}
                <ChartCard
                    title="Tenant Status"
                    sub="Subscription state breakdown"
                >
                    <ResponsiveContainer width="100%" height={180}>
                        <PieChart>
                            <Pie
                                data={tenants.status_breakdown.filter(
                                    (d) => d.value > 0,
                                )}
                                cx="50%"
                                cy="50%"
                                innerRadius={50}
                                outerRadius={70}
                                paddingAngle={3}
                                dataKey="value"
                                label={false}
                            >
                                {tenants.status_breakdown.map((entry, i) => (
                                    <Cell key={i} fill={entry.color} />
                                ))}
                            </Pie>
                            <Tooltip contentStyle={ct.tooltip.contentStyle} />
                            <Legend
                                formatter={(value) => (
                                    <span
                                        style={{
                                            fontSize: 11,
                                            color: ct.tick.fill,
                                        }}
                                    >
                                        {value}
                                    </span>
                                )}
                            />
                        </PieChart>
                    </ResponsiveContainer>
                </ChartCard>

                {/* Country breakdown */}
                <ChartCard title="Top Countries" sub="Tenants by country">
                    {tenants.countries.length === 0 ? (
                        <p className="text-muted-foreground py-8 text-center text-xs">
                            No data
                        </p>
                    ) : (
                        <div className="space-y-2.5 pt-1">
                            {tenants.countries.map((c) => (
                                <HBar
                                    key={c.country}
                                    label={c.country}
                                    count={c.count}
                                    max={maxCountry}
                                    color="bg-sky-500"
                                />
                            ))}
                        </div>
                    )}
                </ChartCard>
            </div>

            {/* Cohort retention */}
            <ChartCard
                title="Cohort Retention"
                sub="% of each signup month's subscriptions still active N months later"
            >
                <CohortTable cohorts={cohorts} />
            </ChartCard>
        </Section>
    );
}
