
// Reports Module

function Reports() {
  const [period, setPeriod] = React.useState('6m');
  const [events, setEvents] = React.useState([]);
  const [budgets, setBudgets] = React.useState([]);
  const [freelancers, setFreelancers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg) => { setToast({ msg }); setTimeout(() => setToast(null), 3000); };

  React.useEffect(() => {
    Promise.all([
      sb.from('events').select('*').order('event_date', { ascending: false }),
      sb.from('budgets').select('*').order('issued_date', { ascending: false }),
      sb.from('freelancers').select('*'),
    ]).then(([ev, bud, fr]) => {
      setEvents(ev.data || []);
      setBudgets(bud.data || []);
      setFreelancers(fr.data || []);
      setLoading(false);
    });
  }, []);

  const fmtMoney = (v) => {
    const n = parseFloat(v) || 0;
    if (n >= 1000000) return `R$ ${(n / 1000000).toFixed(1)}M`;
    if (n >= 1000) return `R$ ${(n / 1000).toFixed(0)}k`;
    return `R$ ${n.toLocaleString('pt-BR')}`;
  };

  const now = new Date();

  // Compute revenue by last 6 months from approved budgets
  const revenueByMonth = (() => {
    const months = period === '3m' ? 3 : period === '12m' ? 12 : 6;
    const result = [];
    for (let i = months - 1; i >= 0; i--) {
      const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const label = d.toLocaleDateString('pt-BR', { month: 'short' }).replace('.', '');
      const yStart = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-01';
      const last = new Date(d.getFullYear(), d.getMonth() + 1, 0);
      const yEnd = last.getFullYear() + '-' + String(last.getMonth() + 1).padStart(2, '0') + '-' + String(last.getDate()).padStart(2, '0');
      const total = budgets
        .filter(b => b.status === 'Aprovado' && b.issued_date && b.issued_date >= yStart && b.issued_date <= yEnd)
        .reduce((s, b) => s + (parseFloat(b.total) || 0), 0);
      result.push({ label, value: total });
    }
    return result;
  })();

  // KPIs from real data
  const approvedBudgets = budgets.filter(b => b.status === 'Aprovado');
  const totalRevenue = approvedBudgets.reduce((s, b) => s + (parseFloat(b.total) || 0), 0);
  const completedEvents = events.filter(e => e.status === 'Concluído').length;
  const activeFreelancers = freelancers.filter(f => f.status === 'Ativo' || f.status === 'Escalado').length;
  const pendingBudgets = budgets.filter(b => b.status === 'Pendente' || b.status === 'Em análise').length;

  const kpis = [
    { label: 'Receita aprovada', value: totalRevenue > 0 ? fmtMoney(totalRevenue) : '—', color: DS.colors.primary, icon: 'budget' },
    { label: 'Eventos concluídos', value: String(completedEvents), color: DS.colors.success, icon: 'calendar' },
    { label: 'Freelancers ativos', value: String(activeFreelancers), color: '#8B5CF6', icon: 'users' },
    { label: 'Orçamentos pendentes', value: String(pendingBudgets), color: DS.colors.warning, icon: 'clock' },
  ];

  // Top events by budget
  const topEvents = [...events]
    .sort((a, b) => (parseFloat(b.budget_estimate || b.budget || 0)) - (parseFloat(a.budget_estimate || a.budget || 0)))
    .slice(0, 5);

  // Category breakdown from events
  const CAT_COLORS = ['#3B82F6', '#10B981', '#8B5CF6', '#F59E0B', '#EF4444'];
  const catCounts = {};
  const catRevenue = {};
  events.forEach(e => {
    const t = e.event_type || e.type || 'Outros';
    catCounts[t] = (catCounts[t] || 0) + 1;
    catRevenue[t] = (catRevenue[t] || 0) + (parseFloat(e.budget_estimate || e.budget || 0));
  });
  const totalCatRevenue = Object.values(catRevenue).reduce((s, v) => s + v, 0) || 1;
  const categoryBreakdown = Object.entries(catRevenue)
    .sort((a, b) => b[1] - a[1])
    .map(([label, value], i) => ({ label, value, pct: Math.round((value / totalCatRevenue) * 100), color: CAT_COLORS[i % CAT_COLORS.length] }));

  // Freelancer performance from payments JSONB
  const freelancerPerf = freelancers
    .map(f => {
      const payments = Array.isArray(f.payments) ? f.payments : [];
      const totalPaid = payments.reduce((s, p) => s + (parseFloat(p.valor) || 0), 0);
      return { name: f.name, role: f.role || f.specialty || '—', events: payments.length, paid: totalPaid };
    })
    .filter(f => f.paid > 0 || f.events > 0)
    .sort((a, b) => b.paid - a.paid)
    .slice(0, 5);

  const statusVariant = { 'Confirmado': 'success', 'Em andamento': 'primary', 'Planejamento': 'warning', 'Concluído': 'success', 'Orçamento': 'default' };

  if (loading) {
    return (
      <div>
        <div style={{ marginBottom: 28 }}>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Relatórios</h1>
        </div>
        <Spinner />
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Relatórios</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>Análise de desempenho e resultados</p>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <div style={{ display: 'flex', gap: 2, background: '#F1F5F9', padding: 3, borderRadius: DS.radius.sm }}>
            {[['3m', '3 meses'], ['6m', '6 meses'], ['12m', '12 meses']].map(([val, label]) => (
              <button key={val} onClick={() => setPeriod(val)} style={{
                padding: '5px 12px', borderRadius: 6, border: 'none', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                background: period === val ? '#fff' : 'transparent', color: period === val ? DS.colors.text : DS.colors.textSec,
                boxShadow: period === val ? DS.shadow.sm : 'none', transition: 'all 0.15s',
              }}>{label}</button>
            ))}
          </div>
          <Btn variant="secondary" icon="download" size="sm" onClick={() => showToast('Exportando PDF...')}>PDF</Btn>
          <Btn variant="secondary" icon="grid" size="sm" onClick={() => showToast('Exportando Excel...')}>Excel</Btn>
        </div>
      </div>

      {/* KPI cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {kpis.map(k => (
          <Card key={k.label} style={{ padding: '20px 24px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>{k.label}</div>
                <div style={{ fontSize: 26, fontWeight: 800, color: DS.colors.text, letterSpacing: '-0.02em' }}>{k.value}</div>
              </div>
              <div style={{ width: 40, height: 40, borderRadius: DS.radius.sm, background: k.color + '15', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={k.icon} size={18} color={k.color} />
              </div>
            </div>
          </Card>
        ))}
      </div>

      {/* Revenue + category breakdown */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
        <Card style={{ padding: 24 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text, marginBottom: 4 }}>Faturamento mensal</div>
          <div style={{ fontSize: 12, color: DS.colors.textSec, marginBottom: 20 }}>Orçamentos aprovados por mês</div>
          {revenueByMonth.some(d => d.value > 0) ? (
            <MiniBarChart data={revenueByMonth} color="#3B82F6" height={140} />
          ) : (
            <div style={{ textAlign: 'center', padding: '32px 0', color: DS.colors.textMuted, fontSize: 13 }}>
              <Icon name="budget" size={32} color={DS.colors.border} />
              <div style={{ marginTop: 10 }}>Nenhum orçamento aprovado ainda</div>
            </div>
          )}
        </Card>

        <Card style={{ padding: 24 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text, marginBottom: 4 }}>Breakdown por categoria</div>
          <div style={{ fontSize: 12, color: DS.colors.textSec, marginBottom: 20 }}>Receita estimada por tipo de evento</div>
          {categoryBreakdown.length > 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {categoryBreakdown.slice(0, 4).map(c => (
                <div key={c.label}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 8, height: 8, borderRadius: 2, background: c.color }} />
                      <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{c.label}</span>
                    </div>
                    <div style={{ display: 'flex', gap: 12, fontSize: 13 }}>
                      <span style={{ color: DS.colors.textSec }}>{fmtMoney(c.value)}</span>
                      <span style={{ fontWeight: 700, color: DS.colors.text }}>{c.pct}%</span>
                    </div>
                  </div>
                  <ProgressBar value={c.pct} color={c.color} height={8} />
                </div>
              ))}
            </div>
          ) : (
            <div style={{ textAlign: 'center', padding: '32px 0', color: DS.colors.textMuted, fontSize: 13 }}>
              <Icon name="calendar" size={32} color={DS.colors.border} />
              <div style={{ marginTop: 10 }}>Crie eventos para ver o breakdown</div>
            </div>
          )}
        </Card>
      </div>

      {/* Top events table */}
      <Card style={{ marginBottom: 24 }}>
        <div style={{ padding: '20px 24px', borderBottom: `1px solid ${DS.colors.border}` }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>Eventos por orçamento</div>
        </div>
        {topEvents.length === 0 ? (
          <div style={{ padding: '40px 24px', textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Nenhum evento cadastrado ainda.</div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 1fr 1fr', padding: '10px 24px', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              <span>Evento</span><span>Cliente</span><span>Orçamento</span><span>Status</span>
            </div>
            {topEvents.map((e, i) => (
              <div key={e.id || i} style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 1fr 1fr', padding: '14px 24px', borderBottom: i < topEvents.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center' }}>
                <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{e.name}</span>
                <span style={{ fontSize: 13, color: DS.colors.textSec }}>{e.client_name || '—'}</span>
                <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{fmtMoney(e.budget_estimate || e.budget || 0)}</span>
                <span><Badge variant={statusVariant[e.status] || 'default'}>{e.status || '—'}</Badge></span>
              </div>
            ))}
          </>
        )}
      </Card>

      {/* Freelancer performance */}
      <Card>
        <div style={{ padding: '20px 24px', borderBottom: `1px solid ${DS.colors.border}` }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: DS.colors.text }}>Pagamentos a freelancers</div>
        </div>
        {freelancerPerf.length === 0 ? (
          <div style={{ padding: '40px 24px', textAlign: 'center', fontSize: 13, color: DS.colors.textMuted }}>Nenhum pagamento registrado ainda.</div>
        ) : (
          <>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 0.8fr 1fr', padding: '10px 24px', borderBottom: `1px solid ${DS.colors.border}`, fontSize: 11, fontWeight: 700, color: DS.colors.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              <span>Nome</span><span>Função</span><span>Pagamentos</span><span>Total pago</span>
            </div>
            {freelancerPerf.map((f, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 0.8fr 1fr', padding: '14px 24px', borderBottom: i < freelancerPerf.length - 1 ? `1px solid ${DS.colors.border}` : 'none', alignItems: 'center' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Avatar name={f.name} size={30} />
                  <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{f.name}</span>
                </div>
                <span style={{ fontSize: 13, color: DS.colors.textSec }}>{f.role}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text }}>{f.events}</span>
                <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{fmtMoney(f.paid)}</span>
              </div>
            ))}
          </>
        )}
      </Card>

      {toast && <Toast message={toast.msg} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { Reports });
