'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useUser } from '@/lib/user-context'
import { type Stage } from '@/lib/types'
import { ConfirmTaskModal } from '@/components/ConfirmTaskModal'

interface Tarefa {
  id: number
  cnpj: string | null
  tipo: string
  descricao: string | null
  vencimento: string
  concluida: boolean
  concluida_em: string | null
  criada_em: string
  usuario_nome: string
  razao_social: string | null
  nome_fantasia: string | null
  municipio: string | null
  uf: string | null
  stage: Stage
}

const TIPO_LABELS: Record<string, string> = {
  followup: 'Follow-up',
  reuniao:  'Reunião',
  retorno:  'Retorno',
  outro:    'Outro',
}
const TIPO_COLORS: Record<string, string> = {
  followup: '#5b8fd6',
  reuniao:  '#2f8f7a',
  retorno:  '#d67a4c',
  outro:    '#888',
}

function fmtDate(v: string) {
  return new Date(v + 'T12:00:00').toLocaleDateString('pt-BR')
}
function isOverdue(v: string) {
  return new Date(v + 'T23:59:59') < new Date()
}

// ── Página de Tarefas ─────────────────────────────────────────────────────────
export default function TarefasPage() {
  const user = useUser()
  const [tarefas, setTarefas]     = useState<Tarefa[]>([])
  const [loading, setLoading]     = useState(true)
  const [filtro, setFiltro]       = useState<'abertas' | 'concluidas' | 'todas'>('abertas')
  const [showNew, setShowNew]     = useState(false)
  const [usuarios, setUsuarios]   = useState<{ id: number; nome: string }[]>([])

  async function loadTarefas() {
    setLoading(true)
    const sp = new URLSearchParams()
    if (filtro === 'abertas')    sp.set('concluida', 'false')
    if (filtro === 'concluidas') sp.set('concluida', 'true')
    const res  = await fetch(`/api/tarefas?${sp}`)
    const data = await res.json()
    setTarefas(data)
    setLoading(false)
  }

  useEffect(() => { loadTarefas() }, [filtro]) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (user?.role === 'gestor') {
      fetch('/api/usuarios').then(r => r.json()).then(setUsuarios).catch(() => {})
    }
  }, [user])

  async function marcarConcluida(id: number, concluida: boolean) {
    await fetch(`/api/tarefas/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ concluida }),
    })
    setTarefas(prev => prev.map(t => t.id === id ? { ...t, concluida } : t))
  }

  async function excluir(id: number) {
    if (!confirm('Excluir esta tarefa?')) return
    await fetch(`/api/tarefas/${id}`, { method: 'DELETE' })
    setTarefas(prev => prev.filter(t => t.id !== id))
  }

  async function criarTarefa(data: { tipo: string; descricao: string; vencimento: string; usuario_id?: number }) {
    await fetch('/api/tarefas', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    })
    setShowNew(false)
    loadTarefas()
  }

  const abertas    = tarefas.filter(t => !t.concluida)
  const vencidas   = abertas.filter(t => isOverdue(t.vencimento))

  return (
    <div className="animate-fade">
      <div className="eyebrow"><span className="dash" />Tarefas</div>
      <div className="page-header">
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 300 }}>Tarefas de acompanhamento</h1>
          {user?.role === 'gestor' && (
            <p style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4 }}>
              Visão gestora — todas as tarefas do time
            </p>
          )}
        </div>
        <button className="btn-primary" onClick={() => setShowNew(true)}>+ Nova tarefa</button>
      </div>

      {vencidas.length > 0 && (
        <div style={{
          background: 'rgba(214,122,76,.08)', border: '1px solid rgba(214,122,76,.3)',
          borderRadius: 8, padding: '10px 16px', marginBottom: 16,
          fontSize: 13, color: '#d67a4c', fontFamily: 'var(--font-sans)',
        }}>
          ⚠ {vencidas.length} tarefa{vencidas.length !== 1 ? 's' : ''} vencida{vencidas.length !== 1 ? 's' : ''} — atenção imediata
        </div>
      )}

      {/* filtros */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        {(['abertas', 'concluidas', 'todas'] as const).map(f => (
          <button
            key={f}
            onClick={() => setFiltro(f)}
            style={{
              fontFamily: 'var(--font-mono)', fontSize: 11.5,
              padding: '5px 14px', borderRadius: 20, cursor: 'pointer',
              border: `1px solid ${filtro === f ? 'var(--accent)' : 'var(--border)'}`,
              background: filtro === f ? 'var(--surface-3)' : 'transparent',
              color: filtro === f ? 'var(--text)' : 'var(--muted)',
            }}
          >
            {f === 'abertas' ? 'Em aberto' : f === 'concluidas' ? 'Concluídas' : 'Todas'}
          </button>
        ))}
      </div>

      {loading ? (
        <p style={{ color: 'var(--muted)', fontFamily: 'var(--font-mono)', fontSize: 13 }}>Carregando…</p>
      ) : tarefas.length === 0 ? (
        <div className="panel" style={{ textAlign: 'center', color: 'var(--muted)', padding: '40px 0', fontSize: 13.5 }}>
          Nenhuma tarefa encontrada.
        </div>
      ) : (
        <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
          <table>
            <thead>
              <tr>
                <th style={{ width: 36 }} />
                <th>Lead / Empresa</th>
                <th>Tipo</th>
                <th>Descrição</th>
                <th>Vencimento</th>
                {user?.role === 'gestor' && <th>Responsável</th>}
                <th />
              </tr>
            </thead>
            <tbody>
              {tarefas.map(t => {
                const overdue = !t.concluida && isOverdue(t.vencimento)
                return (
                  <tr key={t.id} style={{ opacity: t.concluida ? .5 : 1 }}>
                    <td style={{ textAlign: 'center' }}>
                      <input
                        type="checkbox"
                        checked={t.concluida}
                        onChange={e => marcarConcluida(t.id, e.target.checked)}
                        style={{ cursor: 'pointer', accentColor: 'var(--accent)' }}
                      />
                    </td>
                    <td>
                      {t.cnpj ? (
                        <Link href={`/leads/${t.cnpj}`} style={{ textDecoration: 'none' }}>
                          <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', textDecoration: t.concluida ? 'line-through' : 'none' }}>
                            {t.razao_social ?? t.cnpj}
                          </div>
                          {t.nome_fantasia && (
                            <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{t.nome_fantasia}</div>
                          )}
                          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--muted-3)' }}>
                            {t.municipio} · {t.uf}
                          </div>
                        </Link>
                      ) : (
                        <span style={{ color: 'var(--muted)', fontStyle: 'italic', fontSize: 12.5 }}>Sem lead vinculado</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={{ fontSize: 12.5, color: 'var(--muted)', maxWidth: 220 }}>
                      {t.descricao ?? '—'}
                    </td>
                    <td style={{
                      fontFamily: 'var(--font-mono)', fontSize: 11.5,
                      color: overdue ? '#d67a4c' : 'var(--muted)',
                      whiteSpace: 'nowrap',
                    }}>
                      {overdue && !t.concluida && <span style={{ marginRight: 5 }}>⚠</span>}
                      {fmtDate(t.vencimento)}
                    </td>
                    {user?.role === 'gestor' && (
                      <td style={{ fontSize: 12.5, color: 'var(--muted)' }}>{t.usuario_nome}</td>
                    )}
                    <td>
                      <button
                        onClick={() => excluir(t.id)}
                        style={{
                          background: 'none', border: 'none',
                          color: 'var(--muted-3)', cursor: 'pointer',
                          fontSize: 14, padding: '4px 8px',
                          borderRadius: 4,
                        }}
                        title="Excluir"
                      >
                        ✕
                      </button>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )}

      {showNew && (
        <ConfirmTaskModal
          onConfirm={criarTarefa}
          onCancel={() => setShowNew(false)}
          gestorMode={user?.role === 'gestor'}
          usuarios={usuarios}
        />
      )}
    </div>
  )
}
