'use client';

import { useState, useCallback } from 'react';

const API = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

// ── Tipos ─────────────────────────────────────────────────────────────
interface Unidade {
  razaoLegal: string;
  cnpj: string;
  proventos: number;
  descontos: number;
  liquido: number;
  headcount: number;
  faturamento?: number;
}

interface Colaborador {
  VINCULO: string;
  NOME: string;
  CPF: string;
  OCUPACAO: string;
  RAZAOLEGAL: string;
  proventos: number;
  descontos: number;
  liquido: number;
}

interface Totais {
  proventos: number;
  descontos: number;
  liquido: number;
  headcount: number;
}

interface DadosFolha {
  totais: Totais;
  unidades: Unidade[];
  colaboradores: Colaborador[];
}

// ── Helpers ───────────────────────────────────────────────────────────
function fmt(v: number) {
  return v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}
function fmtK(v: number) {
  if (v >= 1_000_000) return `R$ ${(v / 1_000_000).toFixed(1)}M`;
  if (v >= 1_000) return `R$ ${(v / 1_000).toFixed(1)}k`;
  return fmt(v);
}
function nomeCurto(nome: string) {
  return nome.replace(/\s*(LTDA|ME|EIRELI|S\.A\.|SA|EPP)\.?$/i, '').trim();
}
function getCompetencia(val: string) {
  const [ano, mes] = val.split('-');
  return `01/${mes}/${ano}`;
}
function formatCPF(cpf: string) {
  const c = (cpf || '').replace(/\D/g, '');
  return c.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
}

// ── Componentes ───────────────────────────────────────────────────────
function KpiCard({ label, value, sub, color }: { label: string; value: string; sub?: string; color: string }) {
  return (
    <div style={{
      background: 'var(--navy2)',
      border: '1px solid var(--border)',
      borderRadius: 12,
      padding: '16px',
      borderBottom: `3px solid ${color}`,
    }}>
      <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.5px', marginBottom: 8 }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 700, color, letterSpacing: '-0.5px' }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function BarChart({ items, color }: { items: { label: string; value: number; display: string }[]; color: string }) {
  const max = Math.max(...items.map((i) => i.value), 1);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      {items.map((it) => (
        <div key={it.label}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
            <span style={{ fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '60%' }} title={it.label}>{it.label}</span>
            <span style={{ color: 'var(--muted)', fontFamily: 'var(--mono)', fontSize: 11 }}>{it.display}</span>
          </div>
          <div style={{ height: 5, background: 'var(--navy3)', borderRadius: 99, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${(it.value / max) * 100}%`, background: color, borderRadius: 99, transition: 'width .5s ease' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

function Panel({ title, sub, children }: { title: string; sub?: string; children: React.ReactNode }) {
  return (
    <div style={{ background: 'var(--navy2)', border: '1px solid var(--border)', borderRadius: 12, padding: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <span style={{ fontWeight: 500, fontSize: 13 }}>{title}</span>
        {sub && <span style={{ fontSize: 11, color: 'var(--muted)' }}>{sub}</span>}
      </div>
      {children}
    </div>
  );
}

// ── Telas ─────────────────────────────────────────────────────────────
type Tab = 'folha' | 'frequencia' | 'colaboradores';

export default function Dashboard() {
  const [tab, setTab] = useState<Tab>('folha');
  const [competencia, setCompetencia] = useState('2026-04');
  const [tipoFolha, setTipoFolha] = useState('1');
  const [loading, setLoading] = useState(false);
  const [erro, setErro] = useState('');
  const [dados, setDados] = useState<DadosFolha | null>(null);
  const [faturamentos, setFaturamentos] = useState<Record<string, string>>({});
  const [atrasos, setAtrasos] = useState<Record<string, string>>({});
  const [faltas, setFaltas] = useState<Record<string, string>>({});

  const carregar = useCallback(async () => {
    setLoading(true);
    setErro('');
    try {
      const comp = getCompetencia(competencia);
      const res = await fetch(`${API}/api/hcm/folha?competencia=${encodeURIComponent(comp)}&tipo=${tipoFolha}`);
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || `Erro ${res.status}`);
      }
      const json: DadosFolha = await res.json();
      setDados(json);
    } catch (e: any) {
      setErro(e.message || 'Erro ao carregar dados');
    } finally {
      setLoading(false);
    }
  }, [competencia, tipoFolha]);

  const unidades = dados?.unidades ?? [];

  return (
    <div style={{ minHeight: '100dvh', display: 'flex', flexDirection: 'column' }}>

      {/* HEADER */}
      <header style={{
        background: 'var(--navy2)',
        borderBottom: '1px solid var(--border)',
        padding: '12px 16px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        position: 'sticky',
        top: 0,
        zIndex: 50,
      }}>
        <div>
          <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.3px' }}>
            <span style={{ color: 'var(--yellow)' }}>HCM</span> Dashboard
          </div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>RAVAPI Soluções</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <input
            type="month"
            value={competencia}
            onChange={(e) => setCompetencia(e.target.value)}
            style={{
              background: 'var(--navy3)',
              border: '1px solid var(--border)',
              color: 'var(--text)',
              borderRadius: 8,
              padding: '5px 8px',
              fontSize: 12,
            }}
          />
          <select
            value={tipoFolha}
            onChange={(e) => setTipoFolha(e.target.value)}
            style={{
              background: 'var(--navy3)',
              border: '1px solid var(--border)',
              color: 'var(--text)',
              borderRadius: 8,
              padding: '5px 8px',
              fontSize: 12,
            }}
          >
            <option value="1">Mensal</option>
            <option value="2">Férias</option>
            <option value="3">13º</option>
            <option value="4">Rescisão</option>
          </select>
          <button
            onClick={carregar}
            disabled={loading}
            style={{
              background: 'var(--yellow)',
              color: 'var(--navy)',
              border: 'none',
              borderRadius: 8,
              padding: '6px 14px',
              fontSize: 12,
              fontWeight: 700,
              cursor: loading ? 'not-allowed' : 'pointer',
              opacity: loading ? 0.7 : 1,
            }}
          >
            {loading ? '...' : 'Carregar'}
          </button>
        </div>
      </header>

      {/* ERRO */}
      {erro && (
        <div style={{
          margin: '12px 16px 0',
          background: 'rgba(224,82,82,0.15)',
          border: '1px solid var(--red)',
          borderRadius: 8,
          padding: '10px 14px',
          fontSize: 13,
          color: 'var(--red)',
        }}>
          {erro}
        </div>
      )}

      {/* TABS */}
      <div style={{
        display: 'flex',
        gap: 0,
        padding: '12px 16px 0',
        borderBottom: '1px solid var(--border)',
      }}>
        {(['folha', 'frequencia', 'colaboradores'] as Tab[]).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            style={{
              background: 'none',
              border: 'none',
              borderBottom: tab === t ? '2px solid var(--yellow)' : '2px solid transparent',
              color: tab === t ? 'var(--yellow)' : 'var(--muted)',
              padding: '8px 14px',
              fontSize: 13,
              fontWeight: tab === t ? 600 : 400,
              cursor: 'pointer',
              textTransform: 'capitalize',
            }}
          >
            {t === 'folha' ? 'Folha' : t === 'frequencia' ? 'Frequência' : 'Colaboradores'}
          </button>
        ))}
      </div>

      {/* CONTEÚDO */}
      <main style={{ flex: 1, padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>

        {/* ── TAB FOLHA ── */}
        {tab === 'folha' && (
          <>
            {/* KPIs */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <KpiCard label="Colaboradores" value={dados ? String(dados.totais.headcount) : '—'} sub="na folha" color="var(--yellow)" />
              <KpiCard label="Líquido total" value={dados ? fmtK(dados.totais.liquido) : '—'} sub="a pagar" color="var(--green)" />
              <KpiCard label="Proventos" value={dados ? fmtK(dados.totais.proventos) : '—'} sub="bruto" color="#4f8ef7" />
              <KpiCard label="Descontos" value={dados ? fmtK(dados.totais.descontos) : '—'} sub="INSS, IR e outros" color="var(--red)" />
            </div>

            {/* Pagamento por unidade */}
            <Panel title="Pagamento líquido por unidade">
              {unidades.length ? (
                <BarChart
                  color="var(--yellow)"
                  items={unidades.map((u) => ({
                    label: nomeCurto(u.razaoLegal),
                    value: u.liquido,
                    display: fmtK(u.liquido),
                  }))}
                />
              ) : (
                <Empty />
              )}
            </Panel>

            {/* % Folha/Faturamento */}
            <Panel title="% Folha sobre faturamento" sub="entrada manual">
              {unidades.length ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {unidades.map((u) => {
                    const key = u.cnpj || u.razaoLegal;
                    const fat = parseFloat(faturamentos[key] || '0');
                    const pct = fat > 0 ? (u.liquido / fat) * 100 : null;
                    const cor = pct == null ? 'var(--muted)' : pct < 25 ? 'var(--green)' : pct < 35 ? 'var(--yellow)' : 'var(--red)';
                    return (
                      <div key={key}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                          <span style={{ fontSize: 12, fontWeight: 500, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            {nomeCurto(u.razaoLegal)}
                          </span>
                          <span style={{ fontSize: 12, color: cor, fontFamily: 'var(--mono)', marginLeft: 8 }}>
                            {pct != null ? `${pct.toFixed(1)}%` : '—'}
                          </span>
                        </div>
                        <input
                          type="number"
                          placeholder="Faturamento R$"
                          value={faturamentos[key] || ''}
                          onChange={(e) => setFaturamentos((f) => ({ ...f, [key]: e.target.value }))}
                          style={{
                            width: '100%',
                            background: 'var(--navy3)',
                            border: '1px solid var(--border)',
                            color: 'var(--text)',
                            borderRadius: 6,
                            padding: '6px 10px',
                            fontSize: 12,
                          }}
                        />
                      </div>
                    );
                  })}
                </div>
              ) : <Empty />}
            </Panel>
          </>
        )}

        {/* ── TAB FREQUÊNCIA ── */}
        {tab === 'frequencia' && (
          <>
            <Panel title="Atrasos por unidade" sub="minutos — manual">
              {unidades.length ? (
                <>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
                    {unidades.map((u) => {
                      const key = u.cnpj || u.razaoLegal;
                      return (
                        <div key={key} style={{ display: 'grid', gridTemplateColumns: '1fr 100px', gap: 8, alignItems: 'center' }}>
                          <span style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{nomeCurto(u.razaoLegal)}</span>
                          <input
                            type="number"
                            placeholder="min"
                            value={atrasos[key] || ''}
                            onChange={(e) => setAtrasos((a) => ({ ...a, [key]: e.target.value }))}
                            style={{ background: 'var(--navy3)', border: '1px solid var(--border)', color: 'var(--text)', borderRadius: 6, padding: '5px 8px', fontSize: 12, width: '100%' }}
                          />
                        </div>
                      );
                    })}
                  </div>
                  <BarChart
                    color="var(--yellow)"
                    items={unidades.map((u) => {
                      const key = u.cnpj || u.razaoLegal;
                      return { label: nomeCurto(u.razaoLegal), value: parseFloat(atrasos[key] || '0'), display: (atrasos[key] || '0') + ' min' };
                    })}
                  />
                </>
              ) : <Empty />}
            </Panel>

            <Panel title="Faltas por unidade" sub="dias — manual">
              {unidades.length ? (
                <>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
                    {unidades.map((u) => {
                      const key = u.cnpj || u.razaoLegal;
                      return (
                        <div key={key} style={{ display: 'grid', gridTemplateColumns: '1fr 100px', gap: 8, alignItems: 'center' }}>
                          <span style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{nomeCurto(u.razaoLegal)}</span>
                          <input
                            type="number"
                            placeholder="dias"
                            value={faltas[key] || ''}
                            onChange={(e) => setFaltas((f) => ({ ...f, [key]: e.target.value }))}
                            style={{ background: 'var(--navy3)', border: '1px solid var(--border)', color: 'var(--text)', borderRadius: 6, padding: '5px 8px', fontSize: 12, width: '100%' }}
                          />
                        </div>
                      );
                    })}
                  </div>
                  <BarChart
                    color="var(--red)"
                    items={unidades.map((u) => {
                      const key = u.cnpj || u.razaoLegal;
                      return { label: nomeCurto(u.razaoLegal), value: parseFloat(faltas[key] || '0'), display: (faltas[key] || '0') + ' dias' };
                    })}
                  />
                </>
              ) : <Empty />}
            </Panel>
          </>
        )}

        {/* ── TAB COLABORADORES ── */}
        {tab === 'colaboradores' && (
          <Panel title="Colaboradores na folha" sub={dados ? `${dados.totais.headcount} registros` : '—'}>
            {dados?.colaboradores.length ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {dados.colaboradores.map((c) => (
                  <div
                    key={c.VINCULO}
                    style={{
                      background: 'var(--navy3)',
                      borderRadius: 8,
                      padding: '10px 12px',
                      border: '1px solid var(--border)',
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ fontWeight: 600, fontSize: 13 }}>{c.NOME}</span>
                      <span style={{ color: 'var(--green)', fontFamily: 'var(--mono)', fontSize: 12, fontWeight: 600 }}>{fmt(c.liquido)}</span>
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--muted)', display: 'flex', gap: 12 }}>
                      <span>{c.OCUPACAO || '—'}</span>
                      <span>•</span>
                      <span>{nomeCurto(c.RAZAOLEGAL)}</span>
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
                      CPF {formatCPF(c.CPF)} · Vínculo {c.VINCULO}
                    </div>
                  </div>
                ))}
              </div>
            ) : <Empty />}
          </Panel>
        )}
      </main>
    </div>
  );
}

function Empty() {
  return (
    <div style={{ textAlign: 'center', padding: '32px 0', color: 'var(--muted)', fontSize: 13 }}>
      Carregue os dados para visualizar
    </div>
  );
}
