
// ============================================================
// JuFlow — Relatórios
// ============================================================
const { useState: useStRL, useMemo: useMemoRL } = React;
const URL2 = window.JFUtils;
const _RCRL = window.Recharts || {};
const BChart = _RCRL.BarChart || (() => null);
const BBar   = _RCRL.Bar || (() => null);
const BX     = _RCRL.XAxis || (() => null);
const BY     = _RCRL.YAxis || (() => null);
const BCG    = _RCRL.CartesianGrid || (() => null);
const BT     = _RCRL.Tooltip || (() => null);
const BRC    = _RCRL.ResponsiveContainer || (({ children, width, height }) => React.createElement('div', { style:{ width, height: height||260 } }, children));
const BPie   = _RCRL.PieChart || (() => null);
const BPiePie= _RCRL.Pie || (() => null);
const BCell  = _RCRL.Cell || (() => null);
const BLeg   = _RCRL.Legend || (() => null);

const Relatorios = ({ appointments }) => {
  const [activeReport, setActiveReport] = useStRL(null);
  const [period, setPeriod] = useStRL('30');

  const cutoff = URL2.addDays(window.JF.TODAY, -Number(period));
  const periodAppts = appointments.filter(a => new Date(a.datetime) >= cutoff && a.status === 'completed');

  // Report data computations
  const revenueByDay = useMemoRL(() => {
    const map = {};
    periodAppts.forEach(a => {
      const d = URL2.formatDate(a.datetime,'dd/MM');
      map[d] = (map[d]||0) + a.price;
    });
    return Object.entries(map).slice(-14).map(([day,value]) => ({ day, value }));
  }, [periodAppts]);

  const serviceFreq = useMemoRL(() => {
    const map = {};
    periodAppts.forEach(a => {
      const s = URL2.getService(a.serviceId);
      if (s) map[s.name] = (map[s.name]||0) + 1;
    });
    return Object.entries(map).sort((a,b)=>b[1]-a[1]).slice(0,8).map(([name,count])=>({ name, count }));
  }, [periodAppts]);

  const profPerf = useMemoRL(() =>
    window.JF.PROFESSIONALS.map(p => {
      const pa = periodAppts.filter(a => a.professionalId === p.id);
      return { name:p.name.split(' ')[0], sessions:pa.length, revenue:pa.reduce((s,a)=>s+a.price,0), color:p.color };
    }).filter(p=>p.sessions>0)
  , [periodAppts]);

  const hourlyHeatmap = useMemoRL(() => {
    const map = {};
    periodAppts.forEach(a => {
      const h = new Date(a.datetime).getHours();
      map[h] = (map[h]||0) + 1;
    });
    return Array.from({length:14},(_,i)=>i+7).map(h => ({ hour:`${String(h).padStart(2,'0')}h`, count:map[h]||0 }));
  }, [periodAppts]);

  const REPORT_CARDS = [
    { id:'faturamento',   title:'Faturamento por Período', icon:'DollarSign', color:'#059669', desc:'Receita diária no período selecionado' },
    { id:'servicos',      title:'Serviços Mais Procurados', icon:'Scissors', color:'#7C3AED', desc:'Ranking de serviços por quantidade de atendimentos' },
    { id:'profissionais', title:'Performance por Profissional', icon:'UserCheck', color:'#0891B2', desc:'Sessões e receita por profissional' },
    { id:'horarios',      title:'Horários Mais Movimentados', icon:'Clock', color:'#FF6B35', desc:'Distribuição de atendimentos por hora do dia' },
    { id:'cancelamentos', title:'Taxa de Cancelamento', icon:'XCircle', color:'#EF4444', desc:'Análise de faltas e cancelamentos' },
    { id:'retorno',       title:'Taxa de Retorno', icon:'RotateCcw', color:'#D97706', desc:'Frequência de retorno dos clientes' },
  ];

  const RTooltip = ({ active, payload, label }) => {
    if (!active || !payload?.length) return null;
    return (
      <div style={{ background:'#fff', border:'1px solid #E2E8F0', borderRadius:8, padding:'8px 12px', fontSize:12 }}>
        <p style={{ margin:'0 0 4px', fontWeight:700, color:'#0A1F44' }}>{label}</p>
        <p style={{ margin:0, color:payload[0]?.fill }}>{URL2.formatCurrency ? URL2.formatCurrency(payload[0]?.value) : payload[0]?.value}</p>
      </div>
    );
  };

  const cancelRate = Math.round((appointments.filter(a=>['cancelled','no_show'].includes(a.status)&&new Date(a.datetime)>=cutoff).length / Math.max(1,appointments.filter(a=>new Date(a.datetime)>=cutoff).length)) * 100);
  const returnRate = 78; // mock

  const renderChart = (id) => {
    switch(id) {
      case 'faturamento':
        return (
          <BRC width="100%" height={260}>
            <BChart data={revenueByDay} margin={{top:5,right:10,left:-10,bottom:0}}>
              <BCG strokeDasharray="3 3" stroke="#F3F4F6" />
              <BX dataKey="day" tick={{fontSize:10,fill:'#9CA3AF'}} tickLine={false} axisLine={false} />
              <BY tick={{fontSize:10,fill:'#9CA3AF'}} tickLine={false} axisLine={false} tickFormatter={v=>'R$'+v} />
              <BT content={<RTooltip />} />
              <BBar dataKey="value" fill="#059669" radius={[4,4,0,0]} />
            </BChart>
          </BRC>
        );
      case 'servicos':
        return (
          <BRC width="100%" height={260}>
            <BChart data={serviceFreq} layout="vertical" margin={{top:0,right:10,left:60,bottom:0}}>
              <BCG strokeDasharray="3 3" stroke="#F3F4F6" />
              <BX type="number" tick={{fontSize:10,fill:'#9CA3AF'}} tickLine={false} axisLine={false} />
              <BY type="category" dataKey="name" tick={{fontSize:11,fill:'#374151'}} tickLine={false} axisLine={false} width={80} />
              <BT formatter={v=>[v+' sessões','']} />
              <BBar dataKey="count" fill="#7C3AED" radius={[0,4,4,0]} />
            </BChart>
          </BRC>
        );
      case 'profissionais':
        return (
          <BRC width="100%" height={260}>
            <BChart data={profPerf} margin={{top:5,right:10,left:-10,bottom:0}}>
              <BCG strokeDasharray="3 3" stroke="#F3F4F6" />
              <BX dataKey="name" tick={{fontSize:11,fill:'#9CA3AF'}} tickLine={false} axisLine={false} />
              <BY tick={{fontSize:10,fill:'#9CA3AF'}} tickLine={false} axisLine={false} />
              <BT formatter={(v,n)=>[n==='sessions'?v+' sessões':URL2.formatCurrency(v),n==='sessions'?'Sessões':'Receita']} />
              <BBar dataKey="sessions" fill="#0891B2" radius={[4,4,0,0]} name="sessions" />
            </BChart>
          </BRC>
        );
      case 'horarios':
        return (
          <BRC width="100%" height={260}>
            <BChart data={hourlyHeatmap} margin={{top:5,right:10,left:-20,bottom:0}}>
              <BCG strokeDasharray="3 3" stroke="#F3F4F6" />
              <BX dataKey="hour" tick={{fontSize:10,fill:'#9CA3AF'}} tickLine={false} axisLine={false} />
              <BY tick={{fontSize:10,fill:'#9CA3AF'}} tickLine={false} axisLine={false} />
              <BT formatter={v=>[v+' atendimentos','']} />
              <BBar dataKey="count" fill="#FF6B35" radius={[4,4,0,0]} />
            </BChart>
          </BRC>
        );
      default:
        return null;
    }
  };

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      {/* Period selector */}
      <div style={{ display:'flex', alignItems:'center', gap:12 }}>
        <span style={{ fontSize:14, fontWeight:600, color:'#374151' }}>Período:</span>
        <div style={{ display:'flex', background:'#F3F4F6', borderRadius:10, padding:3 }}>
          {[['7','7 dias'],['30','30 dias'],['60','60 dias'],['90','90 dias']].map(([v,l]) => (
            <button key={v} onClick={()=>setPeriod(v)} style={{ padding:'6px 14px', borderRadius:8, fontSize:12, fontWeight:600, cursor:'pointer', background:period===v?'#fff':'transparent', color:period===v?'#0A1F44':'#6B7280', border:'none', boxShadow:period===v?'0 1px 3px rgba(0,0,0,.08)':'none', transition:'all .15s' }}>{l}</button>
          ))}
        </div>
        <div style={{ marginLeft:'auto', fontSize:13, color:'#9CA3AF' }}>
          {periodAppts.length} atendimentos realizados no período
        </div>
      </div>

      {/* Quick stats */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <MetricCard title="Atendimentos" value={periodAppts.length} icon="Calendar" color="#7C3AED" trend={12} trendLabel="vs. período anterior" />
        <MetricCard title="Receita" value={URL2.formatCurrency(periodAppts.reduce((s,a)=>s+a.price,0))} icon="TrendingUp" color="#059669" trend={8} trendLabel="vs. período anterior" />
        <MetricCard title="Cancelamentos" value={`${cancelRate}%`} icon="XCircle" color="#EF4444" trend={-2} trendLabel="vs. período anterior" />
        <MetricCard title="Taxa de Retorno" value={`${returnRate}%`} icon="RotateCcw" color="#0891B2" trend={5} trendLabel="vs. período anterior" />
      </div>

      {/* Report cards grid */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))', gap:14 }}>
        {REPORT_CARDS.map(report => (
          <div key={report.id}
            style={{
              background:'#fff', borderRadius:14, overflow:'hidden',
              boxShadow: activeReport===report.id ? `0 8px 32px ${URL2.hexToRgba(report.color,.15)}` : '0 2px 8px rgba(10,31,68,.06)',
              border: `2px solid ${activeReport===report.id ? report.color : 'transparent'}`,
              transition:'all .2s', cursor:'pointer',
            }}
            onClick={() => setActiveReport(activeReport===report.id ? null : report.id)}
          >
            <div style={{ padding:'18px 20px' }}>
              <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
                <div style={{ width:36,height:36,borderRadius:10,background:URL2.hexToRgba(report.color,.1),display:'flex',alignItems:'center',justifyContent:'center' }}>
                  <Icon name={report.icon} size={18} color={report.color} />
                </div>
                <div>
                  <div style={{ fontSize:14, fontWeight:700, color:'#0A1F44' }}>{report.title}</div>
                  <div style={{ fontSize:11, color:'#9CA3AF' }}>{report.desc}</div>
                </div>
              </div>
              {activeReport === report.id ? (
                <div style={{ marginTop:14 }}>
                  {renderChart(report.id) || (
                    <div style={{ textAlign:'center', padding:'20px 0', color:'#9CA3AF', fontSize:13 }}>
                      <Icon name={report.icon} size={32} color="#E2E8F0" />
                      <p style={{ margin:'8px 0 0' }}>Gráfico em desenvolvimento</p>
                    </div>
                  )}
                  <div style={{ marginTop:12, display:'flex', justifyContent:'flex-end' }}>
                    <Button size="sm" variant="secondary" icon="Download" onClick={e=>{e.stopPropagation();addToast('Relatório exportado!','success');}}>Exportar PDF</Button>
                  </div>
                </div>
              ) : (
                <div style={{ display:'flex', alignItems:'center', gap:6, marginTop:8, fontSize:12, color:report.color, fontWeight:600 }}>
                  <Icon name="ChevronDown" size={14} color={report.color} /> Ver relatório
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

Object.assign(window, { Relatorios });
