'use client'

import { useEffect, useState } from 'react'
import { useUser } from '@/lib/user-context'
import { useRouter } from 'next/navigation'

interface Usuario {
  id: number
  nome: string
  email: string
  role: 'gestor' | 'vendedor'
  ativo: boolean
  criado_em: string
}

export default function UsuariosPage() {
  const user   = useUser()
  const router = useRouter()
  const [usuarios, setUsuarios] = useState<Usuario[]>([])
  const [loading, setLoading]   = useState(true)
  const [showNew, setShowNew]   = useState(false)
  const [nNome, setNNome]       = useState('')
  const [nEmail, setNEmail]     = useState('')
  const [nSenha, setNSenha]     = useState('')
  const [nRole, setNRole]       = useState<'vendedor' | 'gestor'>('vendedor')
  const [saving, setSaving]     = useState(false)
  const [error, setError]       = useState('')

  useEffect(() => {
    if (user && user.role !== 'gestor') { router.replace('/dashboard'); return }
    fetch('/api/usuarios')
      .then(r => r.json())
      .then(setUsuarios)
      .finally(() => setLoading(false))
  }, [user, router])

  async function criar(e: React.FormEvent) {
    e.preventDefault()
    setError('')
    setSaving(true)
    const res  = await fetch('/api/usuarios', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ nome: nNome, email: nEmail, senha: nSenha, role: nRole }),
    })
    const data = await res.json()
    setSaving(false)
    if (!res.ok) { setError(data.error); return }
    setShowNew(false)
    setNNome(''); setNEmail(''); setNSenha(''); setNRole('vendedor')
    const res2 = await fetch('/api/usuarios')
    setUsuarios(await res2.json())
  }

  async function toggleAtivo(id: number, ativo: boolean) {
    await fetch('/api/usuarios', {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id, ativo }),
    })
    setUsuarios(prev => prev.map(u => u.id === id ? { ...u, ativo } : u))
  }

  if (loading) return <p style={{ color: 'var(--muted)', padding: 40, fontFamily: 'var(--font-mono)', fontSize: 13 }}>Carregando...</p>

  return (
    <div className="animate-fade">
      <div className="eyebrow"><span className="dash" />Controle de acesso</div>
      <div className="page-header">
        <h1 style={{ fontSize: 26, fontWeight: 300 }}>Usuários</h1>
        <button className="btn-primary" onClick={() => setShowNew(true)}>+ Novo usuário</button>
      </div>

      <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
        <table>
          <thead>
            <tr>
              <th>Nome</th>
              <th>E-mail</th>
              <th>Perfil</th>
              <th>Status</th>
              <th>Desde</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {usuarios.map(u => (
              <tr key={u.id}>
                <td style={{ fontWeight: 500, fontSize: 13 }}>
                  {u.nome}
                  {u.id === user?.id && (
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9, color: 'var(--muted)', marginLeft: 7 }}>VOCÊ</span>
                  )}
                </td>
                <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--muted)' }}>{u.email}</td>
                <td>
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 10.5,
                    padding: '2px 8px', borderRadius: 4,
                    background: u.role === 'gestor' ? 'rgba(91,143,214,.12)' : 'var(--surface-3)',
                    color: u.role === 'gestor' ? '#5b8fd6' : 'var(--muted)',
                    border: `1px solid ${u.role === 'gestor' ? '#5b8fd655' : 'var(--border)'}`,
                  }}>
                    {u.role === 'gestor' ? 'Gestor' : 'Vendedor'}
                  </span>
                </td>
                <td>
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 10.5,
                    color: u.ativo ? '#2f8f7a' : 'var(--muted-3)',
                  }}>
                    {u.ativo ? '● ativo' : '○ inativo'}
                  </span>
                </td>
                <td style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, color: 'var(--muted-3)' }}>
                  {new Date(u.criado_em).toLocaleDateString('pt-BR')}
                </td>
                <td>
                  {u.id !== user?.id && (
                    <button
                      className="btn-secondary"
                      style={{ fontSize: 11.5, padding: '4px 10px' }}
                      onClick={() => toggleAtivo(u.id, !u.ativo)}
                    >
                      {u.ativo ? 'Desativar' : 'Ativar'}
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className={`modal-overlay ${showNew ? 'visible' : ''}`} onClick={() => setShowNew(false)}>
        <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 420 }}>
          <h3>Novo usuário</h3>
          <form onSubmit={criar}>
            <div className="field">
              <label>Nome completo</label>
              <input value={nNome} onChange={e => setNNome(e.target.value)} placeholder="João da Silva" required />
            </div>
            <div className="field">
              <label>E-mail</label>
              <input type="email" value={nEmail} onChange={e => setNEmail(e.target.value)} placeholder="joao@ravapi.com.br" required />
            </div>
            <div className="field">
              <label>Senha inicial</label>
              <input type="password" value={nSenha} onChange={e => setNSenha(e.target.value)} placeholder="Mínimo 6 caracteres" minLength={6} required />
            </div>
            <div className="field">
              <label>Perfil de acesso</label>
              <select value={nRole} onChange={e => setNRole(e.target.value as 'vendedor' | 'gestor')}>
                <option value="vendedor">Vendedor — vê apenas suas tarefas</option>
                <option value="gestor">Gestor — vê todas as tarefas do time</option>
              </select>
            </div>
            {error && (
              <p style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--warn)', marginBottom: 12 }}>{error}</p>
            )}
            <div className="modal-actions">
              <button type="button" className="btn-secondary" onClick={() => setShowNew(false)}>Cancelar</button>
              <button type="submit" className="btn-primary" disabled={saving}>
                {saving ? 'Criando…' : 'Criar usuário'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
