// Caririaçu Guincho — Dashboard Screen

const { useState: useStateD, useEffect: useEffectD } = React;

const MetricCard = ({ icon, iconColor, label, value, sub, onClick }) => (
  <Card style={{
    padding: 20, display: 'flex', flexDirection: 'column', gap: 12,
    cursor: onClick ? 'pointer' : 'default', transition: 'all 0.18s'
  }}
  onClick={onClick}
  onMouseEnter={onClick ? e => { e.currentTarget.style.boxShadow = `0 8px 24px ${iconColor}25`; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.borderColor = iconColor + '50'; } : undefined}
  onMouseLeave={onClick ? e => { e.currentTarget.style.boxShadow = '0 1px 3px rgba(0,0,0,0.07)'; e.currentTarget.style.transform = ''; e.currentTarget.style.borderColor = '#E2E8F0'; } : undefined}>
    <div style={{ width: 40, height: 40, borderRadius: 10, background: iconColor + '18', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <Icon name={icon} size={20} color={iconColor} />
    </div>
    <div>
      <div style={{ fontSize: 28, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif', lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 13, color: '#64748B', marginTop: 4 }}>{label}</div>
      {sub && <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>{sub}</div>}
    </div>
  </Card>
);

const DashboardScreen = ({ onNav }) => {
  const [loading, setLoading] = useStateD(true);
  const [assistencias, setAssistencias] = useStateD([]);
  const [motoristas, setMotoristas] = useStateD([]);
  const [transacoes, setTransacoes] = useStateD([]);
  const [frota, setFrota] = useStateD([]);
  const [backupBannerHidden, setBackupBannerHidden] = useStateD(false);

  useEffectD(() => {
    (async () => {
      const [a, m, t, f] = await Promise.all([
        db.list('assistencias', { order: 'data' }),
        db.list('motoristas', { order: 'nome', asc: true }),
        db.list('transacoes', { order: 'data' }),
        db.list('frota', { order: 'code', asc: true })
      ]);
      setAssistencias(a);
      setMotoristas(m);
      setTransacoes(t);
      setFrota(f);
      setLoading(false);
    })();
  }, []);

  const fmtBRL = v => Number(v || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });

  const stats = {
    abertas: assistencias.filter(a => a.status === 'aberta').length,
    atendimento: assistencias.filter(a => a.status === 'atendimento').length,
    agendadas: assistencias.filter(a => a.status === 'agendada').length,
    finalizadas: assistencias.filter(a => a.status === 'finalizada').length,
    canceladas: assistencias.filter(a => a.status === 'cancelada').length,
    motoristasDisponiveis: motoristas.filter(m => m.status === 'disponivel').length,
    motoristasTotais: motoristas.length,
    ativas: assistencias.filter(a => a.status === 'aberta' || a.status === 'atendimento').length,
  };

  const hojeStr = new Date().toISOString().slice(0,10);
  const transHoje = transacoes.filter(t => t.data === hojeStr);
  const entradasHoje = transHoje.filter(t => t.tipo === 'entrada').reduce((s,t) => s + Number(t.valor||0), 0);
  const saidasHoje = transHoje.filter(t => t.tipo === 'saida').reduce((s,t) => s + Number(t.valor||0), 0);
  const saldoDia = entradasHoje - saidasHoje;

  const alertas = [
    ...assistencias.filter(a => a.status === 'aberta').slice(0, 3).map(a => ({
      id: 'a' + a.id, type: 'danger', msg: `Assistência ${a.numero || '#' + a.id} aberta sem atendimento`, link: 'assistencias'
    })),
    ...frota.filter(f => f.status === 'manutencao').slice(0, 2).map(g => ({
      id: 'f' + g.id, type: 'warning', msg: `Guincho ${g.code} (${g.placa}) em manutenção`, link: 'frota'
    })),
  ];

  if (loading) return (
    <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(180px,1fr))', gap: 16 }}>
        {[...Array(5)].map((_, i) => <Card key={i} style={{ padding: 20, height: 110 }}><Skeleton h={14} rounded={8} style={{ marginBottom: 12 }} /><Skeleton h={32} w="60%" rounded={8} /></Card>)}
      </div>
    </div>
  );

  const isEmpty = assistencias.length === 0 && motoristas.length === 0 && frota.length === 0;

  const lastBackup = localStorage.getItem('caririacu_last_backup');
  const diasDesdeBackup = lastBackup ? Math.floor((new Date() - new Date(lastBackup)) / (1000 * 60 * 60 * 24)) : null;
  const backupVencido = !lastBackup || diasDesdeBackup > 7;

  return (
    <div style={{ padding: 28, display: 'flex', flexDirection: 'column', gap: 24 }}>
      {!isEmpty && backupVencido && !backupBannerHidden && (
        <Card style={{ padding: 18, background: 'linear-gradient(135deg,#FEF2F2 0%,#FECACA 100%)', border: '1px solid #FCA5A5', cursor: 'pointer' }}
          onClick={() => onNav('configuracoes')}
          onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-1px)'}
          onMouseLeave={e => e.currentTarget.style.transform = ''}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 11, background: '#EF4444', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="alert" size={22} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#991B1B' }}>
                {!lastBackup ? '⚠️ Você ainda não fez nenhum backup dos dados' : `⚠️ Último backup há ${diasDesdeBackup} dias — recomendado fazer um novo`}
              </div>
              <div style={{ fontSize: 12, color: '#7F1D1D', marginTop: 2 }}>Clique aqui para ir em Configurações → Backup e baixar um arquivo de segurança</div>
            </div>
            <button onClick={e => { e.stopPropagation(); setBackupBannerHidden(true); }} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#991B1B', padding: 6, borderRadius: 6 }}>
              <Icon name="x" size={16} />
            </button>
          </div>
        </Card>
      )}
      {isEmpty && (
        <Card style={{ padding: 28, background: 'linear-gradient(135deg,#FFFBEB 0%,#FEF3C7 100%)', border: '1px solid #FCD34D' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: '#F59E0B', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="zap" size={28} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 18, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif', marginBottom: 4 }}>Bem-vindo ao Caririaçu Guincho!</div>
              <div style={{ fontSize: 13, color: '#92400E' }}>Comece cadastrando seus motoristas e veículos da frota, depois registre as primeiras assistências.</div>
            </div>
            <Btn variant="primary" icon="users" onClick={() => onNav('motoristas')}>Cadastrar Motoristas</Btn>
          </div>
        </Card>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(180px,1fr))', gap: 16 }}>
        <MetricCard icon="alert" iconColor="#3B82F6" label="Assistências Abertas" value={stats.abertas} onClick={() => onNav('assistencias')} />
        <MetricCard icon="truck" iconColor="#F59E0B" label="Em Atendimento" value={stats.atendimento} onClick={() => onNav('assistencias')} />
        <MetricCard icon="calendar" iconColor="#8B5CF6" label="Agendadas" value={stats.agendadas} onClick={() => onNav('assistencias')} />
        <MetricCard icon="check" iconColor="#10B981" label="Finalizadas" value={stats.finalizadas} sub="histórico total" onClick={() => onNav('assistencias')} />
        <MetricCard icon="x" iconColor="#EF4444" label="Canceladas" value={stats.canceladas} sub="histórico total" onClick={() => onNav('assistencias')} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 16 }}>
        <Card style={{ padding: 20, cursor: 'pointer', transition: 'all 0.18s' }}
          onClick={() => onNav('motoristas')}
          onMouseEnter={e=>{ e.currentTarget.style.boxShadow='0 8px 24px rgba(16,185,129,0.2)'; e.currentTarget.style.transform='translateY(-2px)'; }}
          onMouseLeave={e=>{ e.currentTarget.style.boxShadow='0 1px 3px rgba(0,0,0,0.07)'; e.currentTarget.style.transform=''; }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 13, color: '#64748B', fontWeight: 500 }}>Motoristas Disponíveis</span>
            <span style={{ fontSize: 18, fontWeight: 700, color: '#10B981', fontFamily: 'DM Sans, sans-serif' }}>{stats.motoristasDisponiveis}/{stats.motoristasTotais}</span>
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            {motoristas.slice(0, 6).map(m => (
              <div key={m.id} title={`${m.nome} — ${m.status}`} style={{ opacity: m.status === 'disponivel' ? 1 : 0.35 }}>
                <Avatar initials={m.avatar || m.nome.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} size={28} />
              </div>
            ))}
            {motoristas.length === 0 && <span style={{ fontSize: 12, color: '#94A3B8' }}>Sem motoristas cadastrados</span>}
          </div>
        </Card>
        <Card style={{ padding: 20, cursor: 'pointer', transition: 'all 0.18s' }}
          onClick={() => onNav('financeiro')}
          onMouseEnter={e=>{ e.currentTarget.style.boxShadow='0 8px 24px rgba(16,185,129,0.2)'; e.currentTarget.style.transform='translateY(-2px)'; }}
          onMouseLeave={e=>{ e.currentTarget.style.boxShadow='0 1px 3px rgba(0,0,0,0.07)'; e.currentTarget.style.transform=''; }}>
          <div style={{ fontSize: 13, color: '#64748B', fontWeight: 500, marginBottom: 8 }}>Saldo do Dia</div>
          <div style={{ fontSize: 26, fontWeight: 700, color: saldoDia >= 0 ? '#10B981' : '#EF4444', fontFamily: 'DM Mono, monospace' }}>
            {fmtBRL(saldoDia)}
          </div>
          <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 4 }}>Entradas: {fmtBRL(entradasHoje)} · Saídas: {fmtBRL(saidasHoje)}</div>
        </Card>
        <Card style={{ padding: 20, background: 'linear-gradient(135deg,#0F172A,#1E3A5F)', border: 'none', cursor: 'pointer', transition: 'all 0.18s' }}
          onClick={() => onNav('assistencias')}
          onMouseEnter={e=>{ e.currentTarget.style.boxShadow='0 8px 24px rgba(245,158,11,0.4)'; e.currentTarget.style.transform='translateY(-2px)'; }}
          onMouseLeave={e=>{ e.currentTarget.style.boxShadow='0 1px 3px rgba(0,0,0,0.07)'; e.currentTarget.style.transform=''; }}>
          <div style={{ fontSize: 13, color: '#94A3B8', fontWeight: 500, marginBottom: 8 }}>Assistências Ativas Agora</div>
          <div style={{
            fontSize: 48, fontWeight: 700, color: '#F59E0B', fontFamily: 'DM Sans, sans-serif',
            lineHeight: 1, animation: stats.ativas > 0 ? 'pulse 2s infinite' : 'none'
          }}>{stats.ativas}</div>
          <div style={{ fontSize: 12, color: '#64748B', marginTop: 4 }}>em campo neste momento</div>
        </Card>
      </div>

      {alertas.length > 0 && (
        <Card style={{ borderLeft: '4px solid #EF4444', padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '14px 20px', borderBottom: '1px solid #FEF2F2', display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="alert" size={16} color="#EF4444" />
            <span style={{ fontSize: 14, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Alertas</span>
            <span style={{ background: '#EF4444', color: '#fff', borderRadius: 10, padding: '1px 7px', fontSize: 11, fontWeight: 700 }}>{alertas.length}</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {alertas.map(a => (
              <div key={a.id} onClick={() => onNav(a.link)} style={{
                padding: '11px 20px', display: 'flex', alignItems: 'center', gap: 10,
                borderBottom: '1px solid #F8FAFC', cursor: 'pointer', transition: 'background 0.15s'
              }}
              onMouseEnter={e => e.currentTarget.style.background = '#FFF7ED'}
              onMouseLeave={e => e.currentTarget.style.background = ''}>
                <Icon name="alert" size={14} color={a.type === 'danger' ? '#EF4444' : '#F59E0B'} />
                <span style={{ fontSize: 13, color: '#374151', flex: 1 }}>{a.msg}</span>
                <Icon name="chevronRight" size={14} color="#CBD5E1" />
              </div>
            ))}
          </div>
        </Card>
      )}

      <Card style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#0F172A', fontFamily: 'DM Sans, sans-serif' }}>Últimas Assistências</div>
          <Btn variant="ghost" size="sm" onClick={() => onNav('assistencias')}>Ver todas →</Btn>
        </div>
        {assistencias.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>
            <Icon name="clipboard" size={42} color="#CBD5E1" />
            <div style={{ marginTop: 10 }}>Nenhuma assistência registrada ainda</div>
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: '#F8FAFC' }}>
                  {['Nº','Placa','Cliente','Serviço','Motorista','Status','Valor'].map(h => (
                    <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 12, fontWeight: 600, color: '#64748B', whiteSpace: 'nowrap', borderBottom: '1px solid #E2E8F0' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {assistencias.slice(0, 6).map((a, i) => (
                  <tr key={a.id} style={{ background: i % 2 ? '#F8FAFC' : '#fff', cursor: 'pointer' }}
                    onClick={() => onNav('assistencias')}
                    onMouseEnter={e => e.currentTarget.style.background = '#EFF6FF'}
                    onMouseLeave={e => e.currentTarget.style.background = i % 2 ? '#F8FAFC' : '#fff'}>
                    <td style={{ padding: '10px 16px', fontFamily: 'DM Mono, monospace', fontSize: 12, color: '#3B82F6', fontWeight: 600 }}>{a.numero || `#${a.id}`}</td>
                    <td style={{ padding: '10px 16px' }}>
                      <span style={{ background: '#F1F5F9', borderRadius: 5, padding: '2px 7px', fontFamily: 'DM Mono, monospace', fontSize: 12, color: '#374151', fontWeight: 600 }}>{a.placa || '—'}</span>
                    </td>
                    <td style={{ padding: '10px 16px', color: '#374151', whiteSpace: 'nowrap' }}>{a.cliente}</td>
                    <td style={{ padding: '10px 16px', color: '#374151', whiteSpace: 'nowrap' }}>{a.servico}</td>
                    <td style={{ padding: '10px 16px' }}>
                      {a.motorista_nome ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Avatar initials={a.motorista_avatar || a.motorista_nome.split(' ').map(w=>w[0]).join('').slice(0,2).toUpperCase()} size={24} />
                          <span style={{ color: '#374151', whiteSpace: 'nowrap' }}>{a.motorista_nome.split(' ')[0]}</span>
                        </div>
                      ) : <span style={{ color: '#94A3B8' }}>—</span>}
                    </td>
                    <td style={{ padding: '10px 16px' }}><StatusBadge status={a.status} /></td>
                    <td style={{ padding: '10px 16px', fontFamily: 'DM Mono, monospace', color: '#10B981', fontWeight: 600, textAlign: 'right' }}>R$ {Number(a.valor).toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
};

Object.assign(window, { DashboardScreen });
