'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useUser } from '@/lib/user-context'
import { STAGE_LABELS, type Stage } from '@/lib/types'

interface Stats {
  totals: { total: string; leads: string; prospects: string; ganhos: string }
  byStage: { stage: string; count: string }[]
  byDeteccao: { mes: string; count: string }[]
}

interface Tarefa {
  id: number
  cnpj: string | null
  tipo: string
  descricao: string | null
  vencimento: string
  concluida: boolean
  usuario_nome: string
  razao_social: string | null
  municipio: string | null
  uf: string | null
}

const TIPO_COLORS: Record<string, string> = {
  followup: '#5b8fd6',
  reuniao:  '#2f8f7a',
  retorno:  '#d67a4c',
  outro:    '#888',
}
const TIPO_LABELS: Record<string, string> = {
  followup: 'Follow-up',
  reuniao:  'Reunião',
  retorno:  'Retorno',
  outro:    'Outro',
}

function isOverdue(v: string) {
  return new Date(v + 'T23:59:59') < new Date()
}
function fmtDate(v: string) {
  return new Date(v + 'T12:00:00').toLocaleDateString('pt-BR')
}

export default function DashboardPage() {
  const user = useUser()
  const [data, setData]         = useState<Stats | null>(null)
  const [tarefas, setTarefas]   = useState<Tarefa[]>([])

  useEffect(() => {
    fetch('/api/stats').then(r => r.json()).then(setData)
    fetch('/api/tarefas?concluida=false').then(r => r.json()).then(setTarefas).catch(() => {})
  }, [])

  async function concluir(id: number) {
    await fetch(`/api/tarefas/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ concluida: true }),
    })
    setTarefas(prev => prev.filter(t => t.id !== id))
  }

  if (!data) return <div style={{ color: 'var(--muted)', fontFamily: 'var(--font-mono)', fontSize: 13, padding: '40px 0' }}>Carregando...</div>

  const { totals, byStage, byDeteccao } = data

  // Tarefas: vencidas (overdue) + vencendo hoje e ontem (para não filtrar por data, mostramos todas em aberto ordenadas)
  const pendentes = tarefas.filter(t => isOverdue(t.vencimento) || t.vencimento <= new Date().toISOString().slice(0, 10))
  const vencidas  = tarefas.filter(t => isOverdue(t.vencimento))

  return (
    <div className="animate-fade">
      <div className="eyebrow"><span className="dash" />Dashboard</div>
      <h1 style={{ fontSize: 26, marginBottom: 28, fontWeight: 300 }}>
        Bom dia{user?.primeiroNome ? `, ${user.primeiroNome}` : ''}
      </h1>

      <div className="source-note">
        <span className="badge">RFB</span>
        <div>
          Dados da <b>Receita Federal do Brasil</b> — CNAE alimentação (5611x, 5612x, 5620x).
          Atualização mensal via Dados Abertos CNPJ.
        </div>
      </div>

      {/* stat cards */}
      <div className="stat-grid">
        <div className="stat-card primary">
          <div className="n">{Number(totals.total).toLocaleString('pt-BR')}</div>
          <div className="l">Total de empresas</div>
        </div>
        <div className="stat-card">
          <div className="n">{Number(totals.leads).toLocaleString('pt-BR')}</div>
          <div className="l">Leads ativos</div>
        </div>
        <div className="stat-card">
          <div className="n">{Number(totals.prospects).toLocaleString('pt-BR')}</div>
          <div className="l">Prospects</div>
        </div>
        <div className="stat-card">
          <div className="n">{Number(totals.ganhos).toLocaleString('pt-BR')}</div>
          <div className="l">Fechados</div>
        </div>
      </div>

      {/* tarefas pendentes */}
      {pendentes.length > 0 && (
        <div className="panel" style={{ marginBottom: 20 }}>
          <div className="panel-title">
            <h3>Tarefas pendentes</h3>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {vencidas.length > 0 && (
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10.5,
                  background: 'rgba(214,122,76,.12)', color: '#d67a4c',
                  border: '1px solid rgba(214,122,76,.3)',
                  padding: '2px 8px', borderRadius: 4,
                }}>
                  {vencidas.length} vencida{vencidas.length !== 1 ? 's' : ''}
                </span>
              )}
              <Link href="/tarefas" style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--muted)', textDecoration: 'none' }}>
                ver todas →
              </Link>
            </div>
          </div>
          <table>
            <thead>
              <tr>
                <th style={{ width: 36 }} />
                <th>Lead</th>
                <th>Tipo</th>
                <th>Vencimento</th>
                {user?.role === 'gestor' && <th>Responsável</th>}
              </tr>
            </thead>
            <tbody>
              {pendentes.slice(0, 8).map(t => {
                const overdue = isOverdue(t.vencimento)
                return (
                  <tr key={t.id}>
                    <td style={{ textAlign: 'center' }}>
                      <input
                        type="checkbox"
                        onChange={() => concluir(t.id)}
                        style={{ cursor: 'pointer', accentColor: 'var(--accent)' }}
                      />
                    </td>
                    <td>
                      {t.cnpj ? (
                        <Link href={`/leads/${t.cnpj}`} style={{ textDecoration: 'none' }}>
                          <div style={{ fontSize: 13, color: 'var(--text)' }}>{t.razao_social ?? t.cnpj}</div>
                          <div style={{ fontSize: 11.5, color: 'var(--muted-3)' }}>{t.municipio} · {t.uf}</div>
                        </Link>
                      ) : <span style={{ color: 'var(--muted)', fontSize: 12.5, fontStyle: 'italic' }}>—</span>}
                    </td>
                    <td>
                      <span style={{
                        fontFamily: 'var(--font-mono)', fontSize: 10.5,
                        background: `${TIPO_COLORS[t.tipo]}22`,
                        color: TIPO_COLORS[t.tipo],
                        border: `1px solid ${TIPO_COLORS[t.tipo]}55`,
                        padding: '2px 8px', borderRadius: 4,
                      }}>
                        {TIPO_LABELS[t.tipo] ?? t.tipo}
                      </span>
                    </td>
                    <td style={{
                      fontFamily: 'var(--font-mono)', fontSize: 11.5,
                      color: overdue ? '#d67a4c' : 'var(--muted)',
                      whiteSpace: 'nowrap',
                    }}>
                      {overdue && '⚠ '}{fmtDate(t.vencimento)}
                    </td>
                    {user?.role === 'gestor' && (
                      <td style={{ fontSize: 12.5, color: 'var(--muted)' }}>{t.usuario_nome}</td>
                    )}
                  </tr>
                )
              })}
            </tbody>
          </table>
          {pendentes.length > 8 && (
            <div style={{ padding: '10px 16px', borderTop: '1px solid var(--border)', textAlign: 'center' }}>
              <Link href="/tarefas" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--muted)' }}>
                + {pendentes.length - 8} outras tarefas →
              </Link>
            </div>
          )}
        </div>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* by stage */}
        <div className="panel">
          <div className="panel-title"><h3>Por estágio</h3></div>
          <table>
            <thead>
              <tr>
                <th>Estágio</th>
                <th style={{ textAlign: 'right' }}>Empresas</th>
              </tr>
            </thead>
            <tbody>
              {byStage.map(row => (
                <tr key={row.stage}>
                  <td>
                    <span className={`badge-status st-${row.stage}`}>
                      <span className="bd" />
                      {STAGE_LABELS[row.stage as Stage] ?? row.stage}
                    </span>
                  </td>
                  <td style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                    {Number(row.count).toLocaleString('pt-BR')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* by month */}
        <div className="panel">
          <div className="panel-title"><h3>Detecção por mês</h3></div>
          <table>
            <thead>
              <tr>
                <th>Rodada</th>
                <th style={{ textAlign: 'right' }}>CNPJs novos</th>
              </tr>
            </thead>
            <tbody>
              {byDeteccao.map(row => (
                <tr key={row.mes}>
                  <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{row.mes}</td>
                  <td style={{ textAlign: 'right', fontFamily: 'var(--font-mono)', fontSize: 12 }}>
                    {Number(row.count).toLocaleString('pt-BR')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
