import { getChartTheme } from '@/components/admin/chart-theme';
import StatCard from '@/components/admin/StatCard';
import { useCurrency } from '@/hooks/useCurrency';
import { useIsDark } from '@/hooks/useIsDark';
import { Activity, BarChart3, CreditCard, TrendingUp } from 'lucide-react';
import {
    Bar,
    BarChart,
    CartesianGrid,
    Cell,
    ComposedChart,
    Legend,
    Line,
    Pie,
    PieChart,
    ReferenceLine,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis,
} from 'recharts';
import { ChartCard, Section } from './shared';
import type { MrrMovementMonth, RevenueMetrics } from './types';

// Palette validated for CVD separation and surface contrast in both modes
// (gains stack above zero, losses below, as secondary encoding).
const MOVEMENT_SERIES = (isDark: boolean) =>
    [
        { key: 'new', label: 'New', color: '#059669' },
        {
            key: 'expansion',
            label: 'Expansion',
            color: isDark ? '#6366F1' : '#4F46E5',
        },
        { key: 'reactivation', label: 'Reactivation', color: '#0284C7' },
        { key: 'contraction', label: 'Contraction', color: '#D97706' },
        { key: 'churn', label: 'Churn', color: '#DC2626' },
    ] as const;

function MrrMovementChart({
    data,
    isDark,
    ct,
}: {
    data: MrrMovementMonth[];
    isDark: boolean;
    ct: ReturnType<typeof getChartTheme>;
}) {
    const { base } = useCurrency();
    const series = MOVEMENT_SERIES(isDark);
    const labels: Record<string, string> = Object.fromEntries(
        series.map((s) => [s.key, s.label]),
    );
    labels.net = 'Net';

    return (
        <ResponsiveContainer width="100%" height={240}>
            <ComposedChart
                data={data}
                stackOffset="sign"
                margin={{ top: 4, right: 4, bottom: 0, left: -4 }}
            >
                <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}
                    tickFormatter={(v) =>
                        Math.abs(v) >= 1000
                            ? `${Math.round(v / 1000)}K`
                            : `${v}`
                    }
                />
                <Tooltip
                    contentStyle={ct.tooltip.contentStyle}
                    cursor={ct.tooltip.cursor}
                    formatter={(v, name) => [
                        `${base.code} ${Number(v).toLocaleString()}`,
                        labels[String(name)] ?? String(name),
                    ]}
                />
                <Legend
                    formatter={(value) => (
                        <span style={{ fontSize: 11, color: ct.tick.fill }}>
                            {labels[String(value)] ?? String(value)}
                        </span>
                    )}
                />
                <ReferenceLine y={0} stroke={ct.grid} />
                {series.map((s) => (
                    <Bar
                        key={s.key}
                        dataKey={s.key}
                        stackId="movement"
                        fill={s.color}
                    />
                ))}
                <Line
                    dataKey="net"
                    stroke={ct.tick.fill}
                    strokeWidth={2}
                    dot={{ r: 2 }}
                />
            </ComposedChart>
        </ResponsiveContainer>
    );
}

export default function RevenueSection({
    revenue,
}: {
    revenue: RevenueMetrics;
}) {
    const isDark = useIsDark();
    const ct = getChartTheme(isDark);
    const { base } = useCurrency();

    return (
        <Section title="Revenue" icon={CreditCard}>
            {/* KPI row */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                <StatCard
                    label="Annual Recurring Revenue"
                    value={revenue.arr}
                    sub={`MRR: ${revenue.mrr}`}
                    icon={TrendingUp}
                    iconColor="bg-amber-400/25 text-amber-600 dark:bg-amber-400/15 dark:text-amber-400"
                />
                <StatCard
                    label="Avg Revenue / Account"
                    value={revenue.arpa}
                    sub="Per active subscription"
                    icon={CreditCard}
                    iconColor="bg-primary/25 text-primary dark:bg-primary/20"
                />
                <StatCard
                    label="Yearly Billing"
                    value={`${revenue.yearly_pct}%`}
                    sub="Of active subscriptions"
                    icon={Activity}
                    iconColor="bg-violet-400/25 text-violet-600 dark:bg-violet-400/15 dark:text-violet-400"
                />
                <StatCard
                    label="Invoice Collection"
                    value={revenue.collection_rate}
                    sub="Paid vs invoiced"
                    icon={BarChart3}
                    iconColor="bg-emerald-400/25 text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400"
                />
            </div>

            {/* Charts */}
            <div className="grid gap-4 lg:grid-cols-3">
                {/* MRR trend — spans 2 columns */}
                <ChartCard
                    title="MRR Trend"
                    sub={`Last 12 months (${base.code} thousands)`}
                    className="lg:col-span-2"
                >
                    <ResponsiveContainer width="100%" height={180}>
                        <BarChart
                            data={revenue.mrr_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}
                                tickFormatter={(v) => `${v}K`}
                            />
                            <Tooltip
                                contentStyle={ct.tooltip.contentStyle}
                                cursor={ct.tooltip.cursor}
                                formatter={(v) => [`${base.code} ${v}K`, 'MRR']}
                            />
                            <Bar
                                dataKey="mrr"
                                fill="hsl(17 92% 58%)"
                                radius={[3, 3, 0, 0]}
                            />
                        </BarChart>
                    </ResponsiveContainer>
                </ChartCard>

                {/* Revenue by plan */}
                <ChartCard title="MRR by Plan" sub="Active subscriptions">
                    {revenue.by_plan.length === 0 ? (
                        <p className="text-muted-foreground py-8 text-center text-xs">
                            No active subscriptions
                        </p>
                    ) : (
                        <ResponsiveContainer width="100%" height={180}>
                            <BarChart
                                data={revenue.by_plan}
                                layout="vertical"
                                margin={{
                                    top: 4,
                                    right: 16,
                                    bottom: 0,
                                    left: 8,
                                }}
                            >
                                <XAxis
                                    type="number"
                                    tick={ct.tick}
                                    axisLine={false}
                                    tickLine={false}
                                    tickFormatter={(v) =>
                                        `${Math.round(v / 1000)}K`
                                    }
                                />
                                <YAxis
                                    type="category"
                                    dataKey="plan"
                                    tick={ct.tick}
                                    axisLine={false}
                                    tickLine={false}
                                    width={80}
                                />
                                <Tooltip
                                    contentStyle={ct.tooltip.contentStyle}
                                    cursor={ct.tooltip.cursor}
                                    formatter={(v) => [
                                        `${base.code} ${Number(v).toLocaleString()}`,
                                        'MRR',
                                    ]}
                                />
                                <Bar
                                    dataKey="mrr"
                                    fill="#6366F1"
                                    radius={[0, 3, 3, 0]}
                                />
                            </BarChart>
                        </ResponsiveContainer>
                    )}
                </ChartCard>

                {/* Billing cycle split */}
                <ChartCard title="Billing Cycle Split" sub="Monthly vs yearly">
                    <ResponsiveContainer width="100%" height={180}>
                        <PieChart>
                            <Pie
                                data={revenue.billing_split}
                                cx="50%"
                                cy="50%"
                                innerRadius={52}
                                outerRadius={72}
                                paddingAngle={3}
                                dataKey="value"
                            >
                                {revenue.billing_split.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>
            </div>

            {/* MRR movement waterfall */}
            <ChartCard
                title="MRR Movement"
                sub="Monthly gains (new, expansion, reactivation) vs losses (contraction, churn), with net"
            >
                <MrrMovementChart
                    data={revenue.mrr_movement}
                    isDark={isDark}
                    ct={ct}
                />
            </ChartCard>
        </Section>
    );
}
