const { useState: useStateD, useMemo: useMemoD } = React;

function DashboardPage({ empresas, entregadores, logs, categorias, onNavigate, isLoading }) {
  const MX = window.MX, card = window.card, CatChip = window.CatChip;
  const CAT_COLORS = window.CAT_COLORS;

  const stats = useMemoD(() => {
    const empAtivas = empresas.filter(e => e.status_empresa === 'ATIVO').length;
    const empSusp   = empresas.filter(e => e.status_empresa === 'SUSPENSO').length;
    const empAg     = empresas.filter(e => e.status_empresa === 'AGUARDANDO ATIVAÇÃO').length;
    const entAtivos = entregadores.filter(e => e.status === 'A').length;
    const entAnal   = entregadores.filter(e => e.status === 'E').length;
    const entFila   = entregadores.filter(e => e.status === 'F').length;
    return { empAtivas, empSusp, empAg, entAtivos, entAnal, entFila };
  }, [empresas, entregadores]);

  const recentLogs = logs.slice(0, 6);

  const fmtTime = (iso) => {
    const d = new Date(iso);
    return d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div style={{ padding: '36px 40px 60px', maxWidth: 1280, filter: isLoading ? 'blur(4px)' : 'none', transition: 'filter 0.3s' }}>
      {/* Welcome */}
      <div style={{ marginBottom: 32 }}>
        <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700, color: MX.text, letterSpacing: '-0.025em' }}>
          Bem-vindo<span style={{ color: MX.brand }}>.</span>
        </h1>
        <p style={{ margin: '8px 0 0', fontSize: 14.5, color: MX.muted }}>
          Visão geral do painel — gerencie categorias, status e grupos de empresas e entregadores.
        </p>
      </div>

      {/* Top row: 2 summary cards */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 18 }}>
        {/* Empresas summary */}
        <div style={{ ...card, padding: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: MX.text }}>Empresas</h3>
            <button onClick={() => onNavigate('empresas')} style={{ background: 'transparent', border: 'none', color: MX.brand, fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>Ver todas →</button>
          </div>
          <div style={{ display: 'grid', gap: 14 }}>
            <SummaryRow label="Ativas" value={stats.empAtivas} color={MX.green} />
            <SummaryRow label="Suspensas" value={stats.empSusp} color={MX.red} />
            <SummaryRow label="Aguardando ativação" value={stats.empAg} color={MX.yellow} />
            <div style={{ height: 1, background: MX.border, margin: '4px 0' }}></div>
            <SummaryRow label="Total" value={empresas.length} bold />
          </div>
        </div>

        {/* Entregadores summary */}
        <div style={{ ...card, padding: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: MX.text }}>Entregadores</h3>
            <button onClick={() => onNavigate('entregadores')} style={{ background: 'transparent', border: 'none', color: MX.brand, fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>Ver todos →</button>
          </div>
          <div style={{ display: 'grid', gap: 14 }}>
            <SummaryRow label="Ativos" value={stats.entAtivos} color={MX.green} />
            <SummaryRow label="Em análise" value={stats.entAnal} color={MX.cyan} />
            <SummaryRow label="Fila de espera" value={stats.entFila} color={MX.yellow} />
            <div style={{ height: 1, background: MX.border, margin: '4px 0' }}></div>
            <SummaryRow label="Total" value={entregadores.length} bold />
          </div>
        </div>
      </div>

      {/* Bottom row: activities + categories */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 18 }}>
        {/* Recent activity */}
        <div style={{ ...card, padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '20px 24px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: MX.text }}>Atividades recentes</h3>
            <button onClick={() => onNavigate('logs')} style={{ background: 'transparent', border: 'none', color: MX.brand, fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>Ver tudo →</button>
          </div>
          <div>
            {recentLogs.length === 0 ? (
              <div style={{ padding: '40px', textAlign: 'center', color: MX.dim, fontSize: 13.5 }}>Sem atividades.</div>
            ) : recentLogs.map((log, i) => (
              <div key={log._id} style={{
                padding: '14px 24px',
                borderTop: i === 0 ? `1px solid ${MX.border}` : 'none',
                borderBottom: `1px solid ${MX.border}`,
                display: 'flex', alignItems: 'center', gap: 14,
              }}>
                <div style={{
                  width: 34, height: 34, borderRadius: 10, flexShrink: 0,
                  background: log.tipo === 'empresa' ? MX.brandSoft : MX.blueSoft,
                  color: log.tipo === 'empresa' ? MX.brand : MX.blue,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {log.tipo === 'empresa' ? (
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="7" width="18" height="14" rx="2"/><path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2"/></svg>
                  ) : (
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="8" r="4"/><path d="M6 20v-2a6 6 0 0 1 12 0v2"/></svg>
                  )}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, color: MX.text, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{log.entidade}</div>
                  <div style={{ fontSize: 12.5, color: MX.muted, marginTop: 2 }}>{log.acao}</div>
                </div>
                <div style={{ fontSize: 12, color: MX.dim, fontFamily: "'JetBrains Mono', monospace", flexShrink: 0 }}>{fmtTime(log.dataHora)}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Categories list */}
        <div style={{ ...card, padding: 24, display: 'flex', flexDirection: 'column' }}>
          <h3 style={{ margin: '0 0 18px', fontSize: 16, fontWeight: 700, color: MX.text }}>Categorias</h3>
          <div style={{ display: 'grid', gap: 8, overflowY: 'auto', maxHeight: 380, paddingRight: 4 }}>
            {categorias.map(cat => {
              const c = CAT_COLORS[cat.id] || { fg: MX.dim, bg: "#f1f5f9" };
              return (
                <div key={cat.id} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 12px', borderRadius: 10,
                  background: MX.surface2,
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 9, flexShrink: 0,
                    background: c.bg, color: c.fg,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <window.CategoryIcon id={cat.id} size={16} />
                  </div>
                  <span style={{ fontSize: 13, fontWeight: 600, color: MX.text }}>{cat.nome}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function SummaryRow({ label, value, color, bold }) {
  const MX = window.MX;
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <span style={{ fontSize: 13.5, color: bold ? MX.text : MX.muted, fontWeight: bold ? 600 : 500, display: 'flex', alignItems: 'center', gap: 9 }}>
        {color && <span style={{ width: 7, height: 7, borderRadius: '50%', background: color }}></span>}
        {label}
      </span>
      <span style={{ fontSize: bold ? 18 : 16, fontWeight: bold ? 700 : 600, color: MX.text, letterSpacing: '-0.01em' }}>
        {value.toLocaleString('pt-BR')}
      </span>
    </div>
  );
}

Object.assign(window, { DashboardPage });

