// Reports.jsx
'use strict';
const { useState, useMemo } = React;

const REPORT_TYPES = [
  { id:'faturamento',  label:'Faturamento por Período',        icon:'BarChart2', desc:'Receita e despesas nos últimos meses', color:'#FF6B35' },
  { id:'servicos',     label:'Serviços Mais Realizados',       icon:'Wrench',    desc:'Ranking dos serviços com maior volume', color:'#3B82F6' },
  { id:'clientes',     label:'Clientes que Mais Geram Receita',icon:'Users',     desc:'Top clientes por valor total de OSs', color:'#8B5CF6' },
  { id:'status',       label:'OSs por Status',                 icon:'FileText',  desc:'Distribuição das ordens por status', color:'#10B981' },
  { id:'tecnicos',     label:'Performance por Técnico',        icon:'User',      desc:'OSs concluídas por técnico', color:'#F59E0B' },
];

const PIE_COLORS_REPORT = ['#FF6B35','#3B82F6','#8B5CF6','#10B981','#F59E0B','#EC4899'];

function ReportCard({ r, active, onClick }) {
  return (
    <Card onClick={onClick} className={`p-5 cursor-pointer transition-all ${active?'ring-2 shadow-card-md':'hover:shadow-card-md'}`}
      style={active?{ringColor:r.color}:{}}>
      <div className="flex items-start gap-4">
        <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
          style={{background:r.color+'18'}}>
          <Icon name={r.icon} size={18} color={r.color}/>
        </div>
        <div className="flex-1 min-w-0">
          <h3 className="font-bold text-sm" style={{color:active?r.color:'#0A1F44'}}>{r.label}</h3>
          <p className="text-xs text-slate-400 mt-0.5">{r.desc}</p>
        </div>
        <Icon name="ChevronRight" size={16} color={active?r.color:'#CBD5E1'}/>
      </div>
    </Card>
  );
}

function Reports({ workOrders, transactions, clients }) {
  const [activeReport, setActiveReport] = useState('faturamento');
  const [period, setPeriod] = useState('6m');

  const today = new Date();
  const activeR = REPORT_TYPES.find(r => r.id === activeReport);

  const data = useMemo(() => {
    // Faturamento por período
    const byMonth = {};
    transactions.filter(t=>t.status==='pago').forEach(t=>{
      const mo = t.date?.slice(0,7)||'';
      if(!byMonth[mo]) byMonth[mo]={month:mo,label:`${t.date?.slice(5,7)}/${t.date?.slice(2,4)}`,receita:0,despesas:0};
      if(t.type==='entrada') byMonth[mo].receita+=t.amount;
      else byMonth[mo].despesas+=t.amount;
    });
    const faturamento = Object.values(byMonth).sort((a,b)=>a.month.localeCompare(b.month)).slice(-6);

    // Serviços mais realizados
    const svcCount = {};
    workOrders.forEach(os=>(os.items||[]).forEach(item=>{
      const k=item.desc||'Sem descrição';
      if(!svcCount[k])svcCount[k]={name:k,count:0,total:0};
      svcCount[k].count++;
      svcCount[k].total+=item.total||0;
    }));
    const servicos = Object.values(svcCount).sort((a,b)=>b.count-a.count).slice(0,8)
      .map(s=>({...s,name:s.name.length>22?s.name.slice(0,22)+'…':s.name}));

    // Clientes top
    const cliRevenue = {};
    workOrders.forEach(os=>{
      if(!cliRevenue[os.clientId])cliRevenue[os.clientId]={name:os.clientName,total:0,count:0};
      cliRevenue[os.clientId].total+=os.total||0;
      cliRevenue[os.clientId].count++;
    });
    const topClientes = Object.values(cliRevenue).sort((a,b)=>b.total-a.total).slice(0,6)
      .map(c=>({...c,name:c.name.split(' ').slice(0,2).join(' ')}));

    // OS por status
    const statusData = ['Aberta','Em andamento','Aguardando peça','Concluída','Entregue'].map(s=>({
      name:s, value:workOrders.filter(o=>o.status===s).length,
      fill: {Aberta:'#3B82F6','Em andamento':'#F59E0B','Aguardando peça':'#EC4899',Concluída:'#10B981',Entregue:'#6366F1'}[s]
    })).filter(d=>d.value>0);

    // Por técnico
    const techData = {};
    workOrders.filter(o=>o.status==='Concluída'||o.status==='Entregue').forEach(os=>{
      const t=os.tech||'Não informado';
      if(!techData[t])techData[t]={name:t.split(' ')[0],concluidas:0,total:0};
      techData[t].concluidas++;
      techData[t].total+=os.total||0;
    });
    const tecnicos = Object.values(techData).sort((a,b)=>b.concluidas-a.concluidas);

    return { faturamento, servicos, topClientes, statusData, tecnicos };
  }, [workOrders, transactions]);

  const renderChart = () => {
    if (!window.SimpleBarChart) return <div className="flex items-center justify-center h-64 text-slate-300 text-sm">Carregando gráficos...</div>;
    switch(activeReport) {
      case 'faturamento': return (
        <div>
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            {[
              {label:'Receita Total (6m)', value:fmtCurrency(data.faturamento.reduce((s,d)=>s+d.receita,0)), color:'#FF6B35'},
              {label:'Despesas Totais (6m)', value:fmtCurrency(data.faturamento.reduce((s,d)=>s+d.despesas,0)), color:'#EF4444'},
              {label:'Lucro Bruto (6m)', value:fmtCurrency(data.faturamento.reduce((s,d)=>s+d.receita-d.despesas,0)), color:'#10B981'},
            ].map((c,i)=>(
              <div key={i} className="flex-1 p-4 rounded-xl" style={{background:c.color+'10'}}>
                <p className="text-xs font-semibold text-slate-400 mb-1">{c.label}</p>
                <p className="text-xl font-bold" style={{color:c.color}}>{c.value}</p>
              </div>
            ))}
          </div>
          <SimpleBarChart data={data.faturamento} xKey="label" height={200}
            bars={[{key:'receita',label:'Receita',color:'#FF6B35'},{key:'despesas',label:'Despesas',color:'#FCA5A5'}]}
            formatY={v=>`R$${(v/1000).toFixed(0)}k`} formatTooltip={fmtCurrency}/>
        </div>
      );
      case 'servicos': return (
        <div>
          <p className="text-sm text-slate-400 mb-4">Top {data.servicos.length} serviços realizados</p>
          <HorizontalBarChart data={data.servicos} valueKey="count" labelKey="name" color="#3B82F6" height={260}
            formatValue={v=>`${v}×`}/>
        </div>
      );
      case 'clientes': return (
        <div>
          <p className="text-sm text-slate-400 mb-4">Top {data.topClientes.length} clientes por receita gerada</p>
          <HorizontalBarChart data={data.topClientes} valueKey="total" labelKey="name"
            color={PIE_COLORS_REPORT} height={220} formatValue={v=>fmtCurrency(v)}/>
          <div className="mt-4 space-y-2">
            {data.topClientes.map((c,i)=>(
              <div key={i} className="flex items-center justify-between text-sm px-1">
                <div className="flex items-center gap-2">
                  <span className="w-2 h-2 rounded-full" style={{background:PIE_COLORS_REPORT[i%PIE_COLORS_REPORT.length]}}/>
                  <span className="font-medium text-slate-700">{c.name}</span>
                  <span className="text-xs text-slate-400">{c.count} OS</span>
                </div>
                <span className="font-bold text-slate-700">{fmtCurrency(c.total)}</span>
              </div>
            ))}
          </div>
        </div>
      );
      case 'status': return (
        <div className="flex flex-col md:flex-row items-center gap-6">
          <SimpleDonutChart data={data.statusData.map(s=>({...s,color:s.fill}))} size={200}/>
          <div className="flex-1 space-y-3">
            {data.statusData.map(s=>(
              <div key={s.name} className="flex items-center gap-3">
                <span className="w-3 h-3 rounded-full flex-shrink-0" style={{background:s.fill}}/>
                <div className="flex-1">
                  <div className="flex justify-between text-sm mb-1">
                    <span className="font-medium text-slate-700">{s.name}</span>
                    <span className="font-bold text-slate-700">{s.value}</span>
                  </div>
                  <div className="h-1.5 rounded-full bg-slate-100 overflow-hidden">
                    <div className="h-full rounded-full" style={{width:`${(s.value/workOrders.length)*100}%`,background:s.fill}}/>
                  </div>
                </div>
                <span className="text-xs text-slate-400 w-8 text-right">{Math.round((s.value/workOrders.length)*100)}%</span>
              </div>
            ))}
          </div>
        </div>
      );
      case 'tecnicos': return (
        <div>
          <p className="text-sm text-slate-400 mb-4">OSs concluídas e receita gerada por técnico</p>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {data.tecnicos.map((t,i)=>(
              <Card key={i} className="p-5">
                <div className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold text-white mb-3"
                  style={{background:PIE_COLORS_REPORT[i%PIE_COLORS_REPORT.length]}}>
                  {t.name.slice(0,2).toUpperCase()}
                </div>
                <p className="font-bold text-slate-800 mb-1">{t.name}</p>
                <div className="flex gap-4 text-sm">
                  <div><p className="text-xs text-slate-400">OSs Concluídas</p><p className="font-bold" style={{color:'#10B981'}}>{t.concluidas}</p></div>
                  <div><p className="text-xs text-slate-400">Receita</p><p className="font-bold" style={{color:'#FF6B35'}}>{fmtCurrency(t.total)}</p></div>
                </div>
              </Card>
            ))}
          </div>
        </div>
      );
      default: return null;
    }
  };

  return (
    <div className="anim-fade">
      <PageHeader title="Relatórios" subtitle="Análises e insights do seu negócio"/>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="space-y-3">
          {REPORT_TYPES.map(r=>(
            <ReportCard key={r.id} r={r} active={activeReport===r.id} onClick={()=>setActiveReport(r.id)}/>
          ))}
        </div>
        <Card className="lg:col-span-2 p-6">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h2 className="font-bold text-lg" style={{color:activeR?.color||'#0A1F44'}}>{activeR?.label}</h2>
              <p className="text-xs text-slate-400 mt-0.5">{activeR?.desc}</p>
            </div>
            <Btn variant="outline" icon="Download" size="sm">Exportar PDF</Btn>
          </div>
          {renderChart()}
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Reports });
