import { useState, useEffect } from 'react';
import {
  BarChart2, Trophy, TrendingUp, Users, Package,
  Calendar, RefreshCw,
} from 'lucide-react';
import api from '../services/api';

// ─── Helpers ──────────────────────────────────────────────────────────────────

const fmt  = (v: any) => v != null ? `R$ ${Number(v).toFixed(2).replace('.', ',')}` : '—';
const fmtN = (v: any) => v != null ? Number(v).toLocaleString('pt-BR') : '—';

function today()     { return new Date().toISOString().slice(0, 10); }
function daysAgo(n: number) {
  const d = new Date(); d.setDate(d.getDate() - n);
  return d.toISOString().slice(0, 10);
}

// ─── Aba: Ranking de Equipes (FUT-04) ────────────────────────────────────────

function RankingEquipes({ from, to }: { from: string; to: string }) {
  const [rows, setRows] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    api.get('/cotacoes/admin/relatorio/ranking', { params: { from, to } })
      .then(r => setRows(r.data ?? []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [from, to]);

  if (loading) return (
    <div className="flex items-center justify-center py-16">
      <RefreshCw size={20} className="animate-spin text-amber-400" />
    </div>
  );

  if (!rows.length) return (
    <div className="text-center py-16 text-slate-500 text-sm">
      Nenhum dado encontrado para o período selecionado.
    </div>
  );

  return (
    <div className="flex flex-col gap-3">
      {rows.map((r, i) => (
        <div key={r.equipe_id} className="bg-slate-900 border border-white/10 rounded-2xl p-4 flex items-center gap-4">
          <div className="w-10 h-10 rounded-xl flex items-center justify-center text-lg font-black shrink-0"
            style={{
              background: i === 0 ? '#f59e0b22' : i === 1 ? '#94a3b822' : '#475569/10',
              color: i === 0 ? '#f59e0b' : i === 1 ? '#94a3b8' : '#64748b',
            }}>
            {i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `#${i+1}`}
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-bold text-white">Equipe {r.equipe_id}</p>
            <div className="flex flex-wrap gap-x-4 gap-y-0.5 mt-0.5 text-xs text-slate-400">
              <span>✅ {fmtN(r.pedidos_entregues)} entregues</span>
              <span>📦 {fmtN(r.pedidos_processados)} processados</span>
              {r.media_horas_entrega != null && (
                <span>⏱ {r.media_horas_entrega}h média</span>
              )}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Aba: Relatório de Performance (FUT-05) ───────────────────────────────────

const STATUS_LABEL: Record<string, string> = {
  aguardando: 'Aguardando', separacao: 'Separação', embalagem: 'Embalagem',
  auditoria: 'Auditoria', fiscal: 'Fiscal', expedicao: 'Expedição',
  entregue: 'Entregue', cancelado: 'Cancelado',
};

function RelatorioPerformance({ from, to }: { from: string; to: string }) {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    api.get('/cotacoes/admin/relatorio/setor', { params: { from, to } })
      .then(r => setData(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [from, to]);

  if (loading) return (
    <div className="flex items-center justify-center py-16">
      <RefreshCw size={20} className="animate-spin text-amber-400" />
    </div>
  );

  if (!data) return null;

  const { volume_por_status = [], volume_por_dia = [], top_clientes = [] } = data;
  const totalPedidos = volume_por_status.reduce((s: number, r: any) => s + Number(r.total), 0);
  const totalReceita = volume_por_status.reduce((s: number, r: any) => s + Number(r.receita || 0), 0);

  return (
    <div className="flex flex-col gap-6">
      {/* Cards resumo */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {[
          { label: 'Total de Pedidos', value: fmtN(totalPedidos), icon: Package, color: '#f59e0b' },
          { label: 'Receita Total', value: fmt(totalReceita), icon: TrendingUp, color: '#10b981' },
          { label: 'Entregues', value: fmtN(volume_por_status.find((r: any) => r.status === 'entregue')?.total ?? 0), icon: Trophy, color: '#06b6d4' },
          { label: 'Cancelados', value: fmtN(volume_por_status.find((r: any) => r.status === 'cancelado')?.total ?? 0), icon: Users, color: '#f43f5e' },
        ].map(c => {
          const Icon = c.icon;
          return (
            <div key={c.label} className="bg-slate-900 border border-white/10 rounded-2xl p-4">
              <div className="flex items-center gap-2 mb-2">
                <Icon size={14} style={{ color: c.color }} />
                <p className="text-xs text-slate-400">{c.label}</p>
              </div>
              <p className="text-xl font-black text-white">{c.value}</p>
            </div>
          );
        })}
      </div>

      {/* Volume por status */}
      <div className="bg-slate-900 border border-white/10 rounded-2xl p-4">
        <p className="text-sm font-bold text-white mb-3">Volume por Status</p>
        <div className="flex flex-col gap-2">
          {volume_por_status.map((r: any) => {
            const pct = totalPedidos > 0 ? (Number(r.total) / totalPedidos) * 100 : 0;
            return (
              <div key={r.status} className="flex items-center gap-3">
                <span className="text-xs text-slate-400 w-24 shrink-0">{STATUS_LABEL[r.status] ?? r.status}</span>
                <div className="flex-1 bg-slate-800 rounded-full h-1.5">
                  <div className="h-1.5 rounded-full bg-amber-500" style={{ width: `${pct}%` }} />
                </div>
                <span className="text-xs text-white font-bold w-6 text-right">{fmtN(r.total)}</span>
                <span className="text-xs text-slate-500 w-24 text-right">{fmt(r.receita)}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Volume diário */}
      {volume_por_dia.length > 0 && (
        <div className="bg-slate-900 border border-white/10 rounded-2xl p-4 overflow-x-auto">
          <p className="text-sm font-bold text-white mb-3">Volume por Dia (últimos {volume_por_dia.length} dias)</p>
          <table className="w-full text-xs">
            <thead>
              <tr className="text-slate-500 border-b border-white/10">
                <th className="text-left py-1 pr-4">Data</th>
                <th className="text-right py-1 pr-4">Pedidos</th>
                <th className="text-right py-1">Receita</th>
              </tr>
            </thead>
            <tbody>
              {volume_por_dia.map((r: any) => (
                <tr key={r.dia} className="border-b border-white/5 hover:bg-white/3">
                  <td className="py-1.5 pr-4 text-slate-300">{new Date(r.dia).toLocaleDateString('pt-BR')}</td>
                  <td className="py-1.5 pr-4 text-right font-bold text-white">{fmtN(r.pedidos)}</td>
                  <td className="py-1.5 text-right text-emerald-400">{fmt(r.receita)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Top clientes */}
      {top_clientes.length > 0 && (
        <div className="bg-slate-900 border border-white/10 rounded-2xl p-4">
          <p className="text-sm font-bold text-white mb-3">Top 10 Clientes</p>
          <div className="flex flex-col gap-2">
            {top_clientes.map((r: any, i: number) => (
              <div key={i} className="flex items-center gap-3">
                <span className="text-xs text-slate-500 w-4 text-right shrink-0">{i+1}.</span>
                <span className="text-xs text-white flex-1 truncate">{r.cliente ?? '—'}</span>
                <span className="text-xs text-slate-400">{fmtN(r.pedidos)} ped.</span>
                <span className="text-xs font-bold text-amber-400 w-24 text-right">{fmt(r.gasto)}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Página principal ─────────────────────────────────────────────────────────

type Aba = 'ranking' | 'performance';

const PERIODOS = [
  { label: 'Hoje',   from: () => today(),         to: () => today() },
  { label: '7 dias', from: () => daysAgo(7),      to: () => today() },
  { label: '30 dias',from: () => daysAgo(30),     to: () => today() },
  { label: 'Mês',    from: () => today().slice(0,7)+'-01', to: () => today() },
];

export default function RelatorioPage() {
  const [aba, setAba]   = useState<Aba>('performance');
  const [from, setFrom] = useState(daysAgo(30));
  const [to, setTo]     = useState(today());

  return (
    <div className="max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4 mb-8">
        <div>
          <h1 className="text-2xl font-black text-white flex items-center gap-2">
            <BarChart2 size={22} className="text-amber-400" /> Relatórios
          </h1>
          <p className="text-slate-400 text-sm mt-0.5">Performance operacional e ranking de equipes</p>
        </div>
      </div>

      {/* Filtros de período */}
      <div className="flex flex-wrap gap-2 mb-5">
        {PERIODOS.map(p => (
          <button
            key={p.label}
            onClick={() => { setFrom(p.from()); setTo(p.to()); }}
            className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors
              ${from === p.from() && to === p.to()
                ? 'bg-amber-500 text-black'
                : 'bg-slate-800 text-slate-400 hover:text-white'
              }`}
          >
            {p.label}
          </button>
        ))}
        <div className="flex items-center gap-1 ml-auto">
          <Calendar size={13} className="text-slate-500" />
          <input type="date" value={from} onChange={e => setFrom(e.target.value)}
            className="bg-slate-900 border border-white/10 rounded-lg px-2 py-1 text-xs text-white" />
          <span className="text-slate-500 text-xs">até</span>
          <input type="date" value={to} onChange={e => setTo(e.target.value)}
            className="bg-slate-900 border border-white/10 rounded-lg px-2 py-1 text-xs text-white" />
        </div>
      </div>

      {/* Abas */}
      <div className="flex gap-1 bg-slate-900 rounded-xl p-1 mb-6 w-fit">
        {([
          { id: 'performance', label: 'Performance', icon: TrendingUp },
          { id: 'ranking',     label: 'Ranking Equipes', icon: Trophy },
        ] as { id: Aba; label: string; icon: any }[]).map(t => {
          const Icon = t.icon;
          return (
            <button
              key={t.id}
              onClick={() => setAba(t.id)}
              className={`flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-semibold transition-colors
                ${aba === t.id ? 'bg-amber-500 text-black' : 'text-slate-400 hover:text-white'}`}
            >
              <Icon size={14} /> {t.label}
            </button>
          );
        })}
      </div>

      {aba === 'performance' && <RelatorioPerformance from={from} to={to} />}
      {aba === 'ranking'     && <RankingEquipes from={from} to={to} />}
    </div>
  );
}
