import { useState, useEffect } from 'react';
import {
  LineChart, Line, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
} from 'recharts';
import { Download, TrendingUp, TrendingDown, DollarSign, AlertTriangle } from 'lucide-react';
import { ClubReportService } from '../services/api';

const COLORS = ['#06b6d4', '#8b5cf6', '#10b981', '#f59e0b', '#ef4444'];

const tooltipStyle = {
  contentStyle: {
    background: '#0f172a',
    border: '1px solid rgba(255,255,255,0.08)',
    borderRadius: '12px',
    color: '#f1f5f9',
    fontSize: '12px',
  },
};

function fmtCurrency(v: number) {
  return `R$ ${Number(v || 0).toFixed(2).replace('.', ',')}`;
}

function exportToCsv(rows: any[], filename: string) {
  if (!rows.length) return;
  const headers = Object.keys(rows[0]).join(',');
  const body = rows.map(r =>
    Object.values(r).map(v => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')
  ).join('\n');
  const blob = new Blob([`${headers}\n${body}`], { type: 'text/csv;charset=utf-8;' });
  const url  = URL.createObjectURL(blob);
  const a    = document.createElement('a');
  a.href = url; a.download = filename; a.click();
  URL.revokeObjectURL(url);
}

export default function ClubReportsPage() {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [exporting, setExporting] = useState(false);

  useEffect(() => {
    ClubReportService.get()
      .then(setData)
      .catch(() => setData(null))
      .finally(() => setLoading(false));
  }, []);

  // Merge growth + churn by month
  const growthData = (() => {
    const map: Record<string, any> = {};
    (data?.growth || []).forEach((r: any) => {
      map[r.month] = { month: r.month, new_members: Number(r.new_members), canceled: 0 };
    });
    (data?.churn || []).forEach((r: any) => {
      if (!map[r.month]) map[r.month] = { month: r.month, new_members: 0, canceled: 0 };
      map[r.month].canceled = Number(r.canceled);
    });
    return Object.values(map).sort((a: any, b: any) => a.month.localeCompare(b.month));
  })();

  // MRR per month (aggregate all clubs)
  const mrrByMonth = (() => {
    const map: Record<string, number> = {};
    (data?.mrr || []).forEach((r: any) => {
      map[r.month] = (map[r.month] || 0) + Number(r.mrr);
    });
    return Object.entries(map)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([month, mrr]) => ({ month, mrr }));
  })();

  const latestMrr = mrrByMonth.length > 0 ? mrrByMonth[mrrByMonth.length - 1].mrr : 0;
  const prevMrr   = mrrByMonth.length > 1 ? mrrByMonth[mrrByMonth.length - 2].mrr : 0;
  const mrrGrowth = prevMrr ? (((latestMrr - prevMrr) / prevMrr) * 100).toFixed(1) : null;

  const totalActive   = (data?.overdue || []).reduce((s: number, r: any) => s + Number(r.active), 0);
  const totalSuspended = (data?.overdue || []).reduce((s: number, r: any) => s + Number(r.suspended), 0);
  const churnRate     = totalActive + totalSuspended > 0
    ? ((totalSuspended / (totalActive + totalSuspended)) * 100).toFixed(1)
    : '0';

  const planDist = (data?.planDist || []).map((r: any) => ({
    name: `${r.club_name} — ${r.plan_name}`,
    value: Number(r.total),
  }));

  async function handleExport() {
    setExporting(true);
    try {
      const rows = await ClubReportService.exportCsv();
      exportToCsv(rows, `membros-clubes-${new Date().toISOString().slice(0, 10)}.csv`);
    } catch {
      alert('Erro ao exportar');
    } finally {
      setExporting(false);
    }
  }

  if (loading) {
    return (
      <div className="flex justify-center py-24">
        <div className="w-8 h-8 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      {/* Header */}
      <header className="flex items-start justify-between">
        <div>
          <h2 className="text-4xl font-black text-white tracking-tighter">Relatórios do Clube</h2>
          <p className="text-slate-400 mt-1">MRR, churn, crescimento e distribuição de planos.</p>
        </div>
        <button
          onClick={handleExport}
          disabled={exporting}
          className="flex items-center gap-2 px-5 py-2.5 bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm rounded-xl transition-colors disabled:opacity-50"
        >
          <Download size={16} />
          {exporting ? 'Exportando…' : 'Exportar CSV'}
        </button>
      </header>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-6">
          <div className="p-3 rounded-2xl bg-slate-800 text-cyan-400 w-fit mb-4"><DollarSign size={22} /></div>
          <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">MRR Atual</p>
          <h3 className="text-3xl font-black text-white tabular-nums">{fmtCurrency(latestMrr)}</h3>
          {mrrGrowth !== null && (
            <p className={`text-xs font-bold mt-1 ${Number(mrrGrowth) >= 0 ? 'text-emerald-400' : 'text-rose-400'}`}>
              {Number(mrrGrowth) >= 0 ? '▲' : '▼'} {Math.abs(Number(mrrGrowth))}% vs mês ant.
            </p>
          )}
        </div>

        <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-6">
          <div className="p-3 rounded-2xl bg-slate-800 text-emerald-400 w-fit mb-4"><TrendingUp size={22} /></div>
          <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">Membros Ativos</p>
          <h3 className="text-3xl font-black text-white tabular-nums">{totalActive}</h3>
        </div>

        <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-6">
          <div className="p-3 rounded-2xl bg-slate-800 text-amber-400 w-fit mb-4"><AlertTriangle size={22} /></div>
          <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">Taxa Inadimpl.</p>
          <h3 className="text-3xl font-black text-white tabular-nums">{churnRate}%</h3>
          <p className="text-xs text-slate-500 mt-1">{totalSuspended} suspenso(s)</p>
        </div>

        <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-6">
          <div className="p-3 rounded-2xl bg-slate-800 text-rose-400 w-fit mb-4"><TrendingDown size={22} /></div>
          <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">Cancelamentos</p>
          <h3 className="text-3xl font-black text-white tabular-nums">
            {(data?.churn || []).reduce((s: number, r: any) => s + Number(r.canceled), 0)}
          </h3>
          <p className="text-xs text-slate-500 mt-1">últimos 12 meses</p>
        </div>
      </div>

      {/* MRR Chart */}
      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-8">
        <h3 className="text-base font-black text-white uppercase tracking-wider mb-6">
          MRR — Receita Recorrente Mensal
        </h3>
        <div className="h-52">
          {mrrByMonth.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={mrrByMonth}>
                <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                <XAxis dataKey="month" stroke="#475569" tick={{ fontSize: 11 }} />
                <YAxis stroke="#475569" tick={{ fontSize: 11 }} tickFormatter={v => `R$${v}`} />
                <Tooltip {...tooltipStyle} formatter={(v: any) => [fmtCurrency(v), 'MRR']} />
                <Line type="monotone" dataKey="mrr" stroke="#06b6d4" strokeWidth={2.5} dot={{ fill: '#06b6d4', r: 4 }} />
              </LineChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-full flex items-center justify-center text-slate-600 italic text-sm">Sem dados</div>
          )}
        </div>
      </div>

      {/* Growth + Plan Distribution side by side */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Growth chart */}
        <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-8">
          <h3 className="text-base font-black text-white uppercase tracking-wider mb-6">
            Novos vs Cancelamentos
          </h3>
          <div className="h-52">
            {growthData.length > 0 ? (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={growthData}>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
                  <XAxis dataKey="month" stroke="#475569" tick={{ fontSize: 10 }} />
                  <YAxis stroke="#475569" tick={{ fontSize: 10 }} allowDecimals={false} />
                  <Tooltip {...tooltipStyle} />
                  <Legend wrapperStyle={{ fontSize: 11, color: '#94a3b8' }} />
                  <Bar dataKey="new_members" name="Novos" fill="#10b981" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="canceled"    name="Cancelados" fill="#ef4444" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-full flex items-center justify-center text-slate-600 italic text-sm">Sem dados</div>
            )}
          </div>
        </div>

        {/* Pie chart */}
        <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-8">
          <h3 className="text-base font-black text-white uppercase tracking-wider mb-6">
            Distribuição de Planos
          </h3>
          <div className="h-52 flex items-center">
            {planDist.length > 0 ? (
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={planDist}
                    cx="40%"
                    cy="50%"
                    innerRadius={50}
                    outerRadius={80}
                    dataKey="value"
                    label={({ percent }) => `${(percent * 100).toFixed(0)}%`}
                    labelLine={false}
                  >
                    {planDist.map((_: any, i: number) => (
                      <Cell key={i} fill={COLORS[i % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip {...tooltipStyle} formatter={(v: any) => [v, 'Membros']} />
                  <Legend
                    layout="vertical"
                    align="right"
                    verticalAlign="middle"
                    wrapperStyle={{ fontSize: 11, color: '#94a3b8', maxWidth: '45%' }}
                  />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <div className="w-full flex items-center justify-center text-slate-600 italic text-sm">Sem dados</div>
            )}
          </div>
        </div>
      </div>

      {/* Inadimplência por clube */}
      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-8">
        <h3 className="text-base font-black text-white uppercase tracking-wider mb-6">
          Inadimplência por Clube
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {(data?.overdue || []).map((r: any) => {
            const total = Number(r.active) + Number(r.suspended);
            const pct   = total > 0 ? Math.round((Number(r.suspended) / total) * 100) : 0;
            return (
              <div key={r.club_name} className="bg-slate-800/50 rounded-2xl p-5">
                <div className="flex items-center justify-between mb-3">
                  <span className="font-black text-white">{r.club_name}</span>
                  <span className={`text-sm font-black ${pct > 10 ? 'text-rose-400' : 'text-emerald-400'}`}>{pct}%</span>
                </div>
                <div className="w-full h-2 bg-slate-700 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full ${pct > 10 ? 'bg-rose-500' : 'bg-emerald-500'}`}
                    style={{ width: `${pct}%` }}
                  />
                </div>
                <div className="flex justify-between mt-2 text-xs text-slate-500">
                  <span>{r.active} ativo(s)</span>
                  <span>{r.suspended} suspenso(s)</span>
                </div>
              </div>
            );
          })}
          {(!data?.overdue || data.overdue.length === 0) && (
            <p className="text-slate-600 italic col-span-2">Sem dados de inadimplência</p>
          )}
        </div>
      </div>
    </div>
  );
}
