'use client';

import { useEffect, useState, useMemo } from 'react';
import { motion } from 'framer-motion';
import {
  DollarSign, TrendingUp, Users, Cpu, Crown, Star, Shield,
  ArrowUpRight, ArrowDownRight, FileText,
} from 'lucide-react';
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
  ResponsiveContainer, XAxis, YAxis, Tooltip, CartesianGrid,
} from 'recharts';

// ── Pricing simulation ────────────────────────────────────────────────────────

const MONTHLY_RATE: Record<string, number> = {
  starter:      99,
  professional: 799,
  enterprise:   3499,
};

interface EnrichedUser {
  id: string;
  email: string;
  name: string | null;
  role: string;
  tier: string;
  createdAt: string;
  projectCount: number;
  totalTokens: number;
}

function buildRevenueChart(users: EnrichedUser[]) {
  const months: { label: string; revenue: number; clients: number }[] = [];
  const now = new Date();
  for (let i = 11; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const label = d.toLocaleDateString('en-GB', { month: 'short', year: '2-digit' });
    const activeClients = users.filter(u => {
      if (u.role !== 'client') return false;
      return new Date(u.createdAt) <= new Date(d.getFullYear(), d.getMonth() + 1, 0);
    });
    const revenue = activeClients.reduce((s, u) => s + (MONTHLY_RATE[u.tier] ?? 0), 0);
    months.push({ label, revenue, clients: activeClients.length });
  }
  return months;
}

function ChartTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null;
  return (
    <div className="glass rounded-lg p-3 text-xs border border-border shadow-xl">
      <p className="text-muted mb-1">{label}</p>
      {payload.map((p: any) => (
        <p key={p.name} className="font-semibold text-foreground">
          {p.name === 'revenue' ? `€${p.value.toLocaleString()}` : `${p.value} clients`}
        </p>
      ))}
    </div>
  );
}

const PIE_COLORS = { starter: '#38bdf8', professional: '#a78bfa', enterprise: '#fbbf24' };

export default function FinanceDashboard() {
  const [users, setUsers] = useState<EnrichedUser[]>([]);
  const [byTier, setByTier] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);
  const [revenueView, setRevenueView] = useState<'area' | 'bar'>('area');

  useEffect(() => {
    fetch('/api/admin/stats', { credentials: 'include' })
      .then(r => r.json())
      .then(d => { setUsers(d.users); setByTier(d.byTier ?? {}); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const clients = useMemo(() => users.filter(u => u.role === 'client'), [users]);

  const mrr = useMemo(() =>
    clients.reduce((s, u) => s + (MONTHLY_RATE[u.tier] ?? 0), 0),
    [clients],
  );
  const arr = mrr * 12;
  const totalTokens = useMemo(() => users.reduce((s, u) => s + u.totalTokens, 0), [users]);
  const avgRevenuePerClient = clients.length > 0 ? Math.round(mrr / clients.length) : 0;

  const revenueChart = useMemo(() => buildRevenueChart(users), [users]);
  const prevMrr = revenueChart.at(-2)?.revenue ?? 0;
  const mrrGrowth = prevMrr > 0 ? Math.round(((mrr - prevMrr) / prevMrr) * 100) : 0;

  const pieData = (['starter', 'professional', 'enterprise'] as const)
    .map(t => ({ name: t, value: byTier[t] ?? 0 }))
    .filter(d => d.value > 0);

  if (loading) return (
    <div className="flex items-center justify-center h-64">
      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-accent" />
    </div>
  );

  return (
    <div className="space-y-5">

      {/* Header */}
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
        className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <DollarSign className="w-6 h-6 text-accent-light" /> Finance
          </h2>
          <p className="text-sm text-muted mt-1">Revenue, subscriptions, and billing overview</p>
        </div>
        <span className="text-[11px] text-muted glass-light px-3 py-1.5 rounded-full border border-border">
          Revenue based on subscription tiers
        </span>
      </motion.div>

      {/* KPI cards */}
      <div className="grid grid-cols-4 gap-3">
        {[
          {
            label: 'MRR', value: `€${mrr.toLocaleString()}`,
            sub: `${mrrGrowth >= 0 ? '+' : ''}${mrrGrowth}% vs last month`,
            trend: mrrGrowth >= 0, icon: DollarSign, color: 'text-accent-light',
          },
          {
            label: 'ARR', value: `€${arr.toLocaleString()}`,
            sub: 'Projected annual recurring', trend: true, icon: TrendingUp, color: 'text-green-400',
          },
          {
            label: 'Active Clients', value: clients.length,
            sub: `Avg €${avgRevenuePerClient}/mo per client`, trend: null, icon: Users, color: 'text-purple-400',
          },
          {
            label: 'Total Tokens Consumed', value: totalTokens >= 1_000_000 ? `${(totalTokens / 1_000_000).toFixed(1)}M` : `${(totalTokens / 1000).toFixed(0)}k`,
            sub: 'across all projects', trend: null, icon: Cpu, color: 'text-sky-400',
          },
        ].map((c, i) => {
          const Icon = c.icon;
          return (
            <motion.div key={c.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.04 }}
              className="glass rounded-xl p-5">
              <div className="flex items-center gap-2 mb-3">
                <Icon className={`w-4 h-4 ${c.color}`} />
                <p className="text-[10px] text-muted uppercase tracking-wider font-medium">{c.label}</p>
              </div>
              <p className="text-2xl font-bold text-foreground">{c.value}</p>
              <p className={`text-[11px] mt-1 flex items-center gap-1 ${
                c.trend === true ? 'text-green-400' : c.trend === false ? 'text-red-400' : 'text-muted'
              }`}>
                {c.trend === true && <ArrowUpRight className="w-3 h-3" />}
                {c.trend === false && <ArrowDownRight className="w-3 h-3" />}
                {c.sub}
              </p>
            </motion.div>
          );
        })}
      </div>

      {/* Tier pricing breakdown */}
      <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.18 }}
        className="glass rounded-xl p-5">
        <h3 className="text-sm font-semibold text-foreground mb-4">Subscription Breakdown</h3>
        <div className="grid grid-cols-3 gap-4">
          {([
            { tier: 'starter',      icon: Star,   color: 'text-sky-400',    bg: 'bg-sky-500/10',    border: 'border-sky-500/20'    },
            { tier: 'professional', icon: Crown,  color: 'text-purple-400', bg: 'bg-purple-500/10', border: 'border-purple-500/20' },
            { tier: 'enterprise',   icon: Shield, color: 'text-amber-400',  bg: 'bg-amber-500/10',  border: 'border-amber-500/20'  },
          ] as const).map(({ tier, icon: Icon, color, bg, border }) => {
            const count = byTier[tier] ?? 0;
            const tierMrr = count * (MONTHLY_RATE[tier] ?? 0);
            const pct = mrr > 0 ? Math.round((tierMrr / mrr) * 100) : 0;
            return (
              <div key={tier} className={`rounded-xl p-4 ${bg} border ${border}`}>
                <div className="flex items-center justify-between mb-3">
                  <span className={`flex items-center gap-1.5 text-xs font-semibold capitalize ${color}`}>
                    <Icon className="w-3.5 h-3.5" />{tier}
                  </span>
                  <span className="text-[11px] text-muted">€{MONTHLY_RATE[tier]}/mo</span>
                </div>
                <p className="text-2xl font-bold text-foreground">{count}</p>
                <p className="text-[10px] text-muted mt-0.5">clients · €{tierMrr.toLocaleString()} MRR</p>
                <div className="mt-3 h-1 rounded-full bg-surface overflow-hidden">
                  <div className={`h-full rounded-full ${color}`} style={{ width: `${pct}%`, background: 'currentColor' }} />
                </div>
                <p className="text-[10px] text-muted mt-1">{pct}% of MRR</p>
              </div>
            );
          })}
        </div>
      </motion.div>

      {/* Revenue chart + pie */}
      <div className="grid grid-cols-3 gap-4">
        <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.22 }}
          className="col-span-2 glass rounded-xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
              <TrendingUp className="w-4 h-4 text-accent-light" /> Monthly Revenue
            </h3>
            <div className="flex gap-1 bg-surface rounded-lg p-1">
              {(['area', 'bar'] as const).map(v => (
                <button key={v} onClick={() => setRevenueView(v)}
                  className={`px-3 py-1 rounded-md text-xs font-medium cursor-pointer transition-all capitalize ${
                    revenueView === v ? 'bg-accent/20 text-accent-light' : 'text-muted hover:text-foreground'
                  }`}>{v}</button>
              ))}
            </div>
          </div>
          <ResponsiveContainer width="100%" height={200}>
            {revenueView === 'area' ? (
              <AreaChart data={revenueChart} margin={{ top: 5, right: 5, bottom: 0, left: 0 }}>
                <defs>
                  <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="var(--color-accent)" stopOpacity={0.3} />
                    <stop offset="95%" stopColor="var(--color-accent)" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
                <XAxis dataKey="label" tick={{ fontSize: 10, fill: 'var(--color-muted)' }} tickLine={false} axisLine={false} />
                <YAxis tick={{ fontSize: 10, fill: 'var(--color-muted)' }} tickLine={false} axisLine={false}
                  tickFormatter={(v: number) => `€${v >= 1000 ? `${(v/1000).toFixed(0)}k` : v}`} />
                <Tooltip content={<ChartTooltip />} />
                <Area type="monotone" dataKey="revenue" name="revenue" stroke="var(--color-accent)" strokeWidth={2} fill="url(#revGrad)" dot={false} />
              </AreaChart>
            ) : (
              <BarChart data={revenueChart} margin={{ top: 5, right: 5, bottom: 0, left: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
                <XAxis dataKey="label" tick={{ fontSize: 10, fill: 'var(--color-muted)' }} tickLine={false} axisLine={false} />
                <YAxis tick={{ fontSize: 10, fill: 'var(--color-muted)' }} tickLine={false} axisLine={false}
                  tickFormatter={(v: number) => `€${v >= 1000 ? `${(v/1000).toFixed(0)}k` : v}`} />
                <Tooltip content={<ChartTooltip />} />
                <Bar dataKey="revenue" name="revenue" fill="var(--color-accent)" radius={[3,3,0,0]} fillOpacity={0.8} />
              </BarChart>
            )}
          </ResponsiveContainer>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.24 }}
          className="glass rounded-xl p-5 flex flex-col">
          <h3 className="text-sm font-semibold text-foreground mb-4">Clients by Tier</h3>
          {pieData.length > 0 ? (
            <>
              <ResponsiveContainer width="100%" height={140}>
                <PieChart>
                  <Pie data={pieData} cx="50%" cy="50%" innerRadius={40} outerRadius={65}
                    dataKey="value" paddingAngle={3}>
                    {pieData.map(d => (
                      <Cell key={d.name} fill={PIE_COLORS[d.name as keyof typeof PIE_COLORS]} fillOpacity={0.85} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value: any, name: any) => [value, name]} />
                </PieChart>
              </ResponsiveContainer>
              <div className="mt-3 space-y-1.5">
                {pieData.map(d => (
                  <div key={d.name} className="flex items-center justify-between text-xs">
                    <div className="flex items-center gap-2">
                      <div className="w-2.5 h-2.5 rounded-full" style={{ background: PIE_COLORS[d.name as keyof typeof PIE_COLORS] }} />
                      <span className="capitalize text-muted">{d.name}</span>
                    </div>
                    <span className="font-semibold text-foreground">{d.value}</span>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <p className="text-xs text-muted italic mt-4">No client data yet.</p>
          )}
        </motion.div>
      </div>

      {/* Invoices */}
      <motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.26 }}
        className="glass rounded-xl p-5">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
            <FileText className="w-4 h-4 text-accent-light" /> Billing History
          </h3>
        </div>
        <div className="flex flex-col items-center justify-center py-8 gap-2 text-center">
          <FileText className="w-8 h-8 text-muted/40 mb-1" />
          <p className="text-sm text-muted font-medium">No billing records yet</p>
          <p className="text-xs text-muted/60">Invoice and payment history will appear here once billing is configured.</p>
        </div>
      </motion.div>

    </div>
  );
}
