// Dashboard.jsx
'use strict';
const { useState, useMemo } = React;

const PIE_COLORS = { 'Aberta':'#3B82F6','Em andamento':'#F59E0B','Aguardando peça':'#EC4899','Concluída':'#10B981','Entregue':'#6366F1' };

function MetricCard({ label, value, sub, icon, iconBg, trend, trendVal, onClick }) {
  const up = trend === 'up';
  return (
    <Card onClick={onClick} className="p-5 hover:shadow-card-md transition-shadow cursor-pointer">
      <div className="flex items-start justify-between mb-4">
        <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: iconBg }}>
          <Icon name={icon} size={19} color="white" />
        </div>
        {trendVal && (
          <div className={`flex items-center gap-1 text-xs font-semibold px-2 py-1 rounded-lg ${up ? 'bg-emerald-50 text-emerald-600' : 'bg-red-50 text-red-500'}`}>
            <Icon name={up ? 'TrendingUp' : 'TrendingDown'} size={12} color={up ? '#059669' : '#EF4444'} />
            {trendVal}
          </div>
        )}
      </div>
      <div className="text-2xl font-bold tracking-tight mb-0.5" style={{ color:'#0A1F44' }}>{value}</div>
      <div className="text-sm font-medium text-slate-500">{label}</div>
      {sub && <div className="text-xs text-slate-400 mt-0.5">{sub}</div>}
    </Card>
  );
}



function Dashboard({ workOrders, appointments, clients, transactions, revenueChart, setPage }) {
  const stats = useMemo(() => {
    const hoje = new Date().toISOString().split('T')[0];
    const mesAtual = hoje.slice(0, 7);
    const abertas   = workOrders.filter(o => o.status === 'Aberta' || o.status === 'Em andamento' || o.status === 'Aguardando peça');
    const concMes   = workOrders.filter(o => o.status === 'Concluída' && o.entryDate?.startsWith(mesAtual));
    const receitaMes = transactions.filter(t => t.type === 'entrada' && t.status === 'pago' && t.date?.startsWith(mesAtual)).reduce((s, t) => s + t.amount, 0);
    const ativos = clients.length;
    const osStatus = Object.entries(
      workOrders.reduce((acc, o) => { acc[o.status] = (acc[o.status]||0)+1; return acc; }, {})
    ).map(([name, value]) => ({ name, value, fill: PIE_COLORS[name]||'#94A3B8' }));
    return { abertas: abertas.length, concMes: concMes.length, receitaMes, ativos, osStatus };
  }, [workOrders, transactions, clients]);

  const proxAgendamentos = [...appointments]
    .filter(a => a.date >= new Date().toISOString().split('T')[0])
    .sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time))
    .slice(0, 5);

  const ultimasOS = [...workOrders]
    .sort((a, b) => b.entryDate?.localeCompare(a.entryDate))
    .slice(0, 5);

  const typeColor = { 'Visita técnica':'#3B82F6','Retirada':'#10B981','Entrega':'#FF6B35','Retorno':'#8B5CF6' };
  const equipIcon = { Smartphone:'Smartphone', Notebook:'Laptop', Desktop:'Monitor', TV:'Tv', Tablet:'Smartphone' };

  return (
    <div className="anim-fade">
      {/* Welcome bar */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold tracking-tight" style={{ color:'#0A1F44' }}>Bom dia, Ademir! 👋</h1>
          <p className="text-sm text-slate-400 mt-0.5">Aqui está o resumo do seu negócio hoje.</p>
        </div>
        <div className="hidden md:flex items-center gap-2 px-4 py-2 rounded-xl border border-slate-200 bg-white text-sm text-slate-500">
          <Icon name="Calendar" size={15} color="#94A3B8" />
          {new Date().toLocaleDateString('pt-BR', { weekday:'long', day:'2-digit', month:'long', year:'numeric' })}
        </div>
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <MetricCard label="OSs em Aberto"      value={stats.abertas}              icon="FileText"    iconBg="#3B82F6" trendVal="+3 hoje" trend="up"   onClick={() => setPage('os')} />
        <MetricCard label="Concluídas no Mês"  value={stats.concMes}              icon="CheckCircle" iconBg="#10B981" trendVal="+12%"   trend="up"   onClick={() => setPage('os')} />
        <MetricCard label="Receita do Mês"     value={fmtCurrency(stats.receitaMes)} icon="DollarSign" iconBg="#FF6B35" trendVal="+8%"  trend="up"   onClick={() => setPage('financeiro')} />
        <MetricCard label="Clientes Ativos"    value={stats.ativos}               icon="Users"       iconBg="#8B5CF6" trendVal="+2"     trend="up"   onClick={() => setPage('clientes')} />
      </div>

      {/* Charts row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-6">
        {/* Revenue chart */}
        <Card className="lg:col-span-2 p-5">
          <div className="flex items-center justify-between mb-5">
            <div>
              <h3 className="font-bold text-base" style={{ color:'#0A1F44' }}>Receita vs. Despesas</h3>
              <p className="text-xs text-slate-400 mt-0.5">Últimos 6 meses</p>
            </div>
            <div className="flex items-center gap-4 text-xs">
              <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full" style={{ background:'#FF6B35' }}/><span className="text-slate-500">Receita</span></span>
              <span className="flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-full" style={{ background:'#E2E8F0' }}/><span className="text-slate-500">Despesas</span></span>
            </div>
          </div>
          <SimpleAreaChart data={revenueChart} xKey="month" height={200}
            lines={[{key:'receita',label:'Receita',color:'#FF6B35'},{key:'despesas',label:'Despesas',color:'#CBD5E1'}]}
            formatY={v=>`R$${(v/1000).toFixed(0)}k`} formatTooltip={fmtCurrency}/>
        </Card>

        {/* Pie chart */}
        <Card className="p-5">
          <h3 className="font-bold text-base mb-1" style={{ color:'#0A1F44' }}>OSs por Status</h3>
          <p className="text-xs text-slate-400 mb-4">Total: {workOrders.length} ordens</p>
          <div className="flex justify-center my-2">
            <SimpleDonutChart data={stats.osStatus.map(s=>({...s,color:s.fill}))} size={160}/>
          </div>
          <div className="flex flex-col gap-1.5 mt-2">
            {stats.osStatus.map(s => (
              <div key={s.name} className="flex items-center justify-between text-xs">
                <div className="flex items-center gap-2">
                  <span className="w-2 h-2 rounded-full" style={{ background: s.fill }}/>
                  <span className="text-slate-600">{s.name}</span>
                </div>
                <span className="font-semibold text-slate-700">{s.value}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Bottom lists */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Próximos agendamentos */}
        <Card className="p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-bold text-base" style={{ color:'#0A1F44' }}>Próximos Agendamentos</h3>
            <button onClick={() => setPage('agenda')} className="text-xs font-semibold hover:underline" style={{ color:'#FF6B35' }}>Ver todos</button>
          </div>
          {proxAgendamentos.length === 0
            ? <EmptyState icon="Calendar" title="Sem agendamentos" message="Nenhum agendamento próximo." />
            : <div className="flex flex-col gap-2">
                {proxAgendamentos.map(a => (
                  <div key={a.id} className="flex items-center gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors">
                    <div className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0"
                      style={{ background: (typeColor[a.type]||'#94A3B8')+'18' }}>
                      <Icon name="Calendar" size={14} color={typeColor[a.type]||'#94A3B8'} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold truncate" style={{ color:'#1E293B' }}>{a.title}</p>
                      <p className="text-xs text-slate-400">{fmtDate(a.date)} às {a.time}</p>
                    </div>
                    <span className="text-xs font-semibold px-2 py-1 rounded-lg whitespace-nowrap"
                      style={{ background:(typeColor[a.type]||'#94A3B8')+'18', color:typeColor[a.type]||'#94A3B8' }}>{a.type}</span>
                  </div>
                ))}
              </div>
          }
        </Card>

        {/* Últimas OSs */}
        <Card className="p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-bold text-base" style={{ color:'#0A1F44' }}>Últimas Ordens de Serviço</h3>
            <button onClick={() => setPage('os')} className="text-xs font-semibold hover:underline" style={{ color:'#FF6B35' }}>Ver todas</button>
          </div>
          <div className="flex flex-col gap-1">
            {ultimasOS.map(os => (
              <div key={os.id} className="flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 transition-colors">
                <div className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background:'#F1F5F9' }}>
                  <Icon name={equipIcon[os.equipment?.type]||'Monitor'} size={13} color="#64748b" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-bold" style={{ color:'#0A1F44' }}>#{os.num}</span>
                    <span className="text-xs text-slate-500 truncate">{os.clientName}</span>
                  </div>
                  <p className="text-xs text-slate-400 truncate">{os.equipment?.brand} {os.equipment?.model}</p>
                </div>
                <StatusBadge status={os.status} size="xs" />
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
