import React, { useState, useEffect } from 'react';
import { Shield, RefreshCw } from 'lucide-react';
import api from '../services/api';

const ACTIONS: Record<string, { label: string; cls: string }> = {
  LOGIN_SUCCESS:    { label: 'Login',             cls: 'bg-emerald-900/30 text-emerald-400' },
  LOGIN_FAILED:     { label: 'Login Falhou',       cls: 'bg-red-900/30 text-red-400' },
  FILE_UPLOAD:      { label: 'Upload',             cls: 'bg-blue-900/30 text-blue-400' },
  FILE_DOWNLOAD:    { label: 'Download',           cls: 'bg-violet-900/30 text-violet-400' },
  FILE_DELETE:      { label: 'Arquivo Removido',   cls: 'bg-red-900/30 text-red-400' },
  USER_CREATED:     { label: 'Usuário Criado',     cls: 'bg-brand-cyan/20 text-brand-cyan' },
  USER_UPDATED:     { label: 'Usuário Editado',    cls: 'bg-yellow-900/30 text-yellow-400' },
  USER_DEACTIVATED: { label: 'Usuário Desativado', cls: 'bg-orange-900/30 text-orange-400' },
};

export default function Audit() {
  const [logs, setLogs]             = useState<any[]>([]);
  const [filter, setFilter]         = useState('');
  const [loading, setLoading]       = useState(false);

  const load = async () => {
    setLoading(true);
    const p = new URLSearchParams({ limit: '300' });
    if (filter) p.set('action', filter);
    const res = await api.get(`/audit?${p}`);
    setLogs(res.data);
    setLoading(false);
  };

  useEffect(() => { load(); }, [filter]);

  return (
    <div className="space-y-5 max-w-7xl">
      <div className="flex items-center gap-3">
        <select value={filter} onChange={e => setFilter(e.target.value)} className="input-field w-auto">
          <option value="">Todas as ações</option>
          {Object.entries(ACTIONS).map(([k, { label }]) => (
            <option key={k} value={k}>{label}</option>
          ))}
        </select>
        <button onClick={load} className="btn-secondary">
          <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
          Atualizar
        </button>
        <span className="text-gray-700 text-sm ml-auto">{logs.length} registro(s)</span>
      </div>

      <div className="card p-0 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-surface-border flex items-center gap-2">
          <Shield size={15} className="text-brand-cyan" />
          <span className="text-white text-sm font-medium">Log de Auditoria</span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="table-header">
              <tr>
                <th>Ação</th>
                <th>Usuário</th>
                <th>Detalhes</th>
                <th>IP</th>
                <th>Data/Hora</th>
              </tr>
            </thead>
            <tbody>
              {logs.length === 0 ? (
                <tr><td colSpan={5} className="text-center text-gray-700 py-14">Nenhum registro encontrado</td></tr>
              ) : logs.map(log => {
                const a = ACTIONS[log.action] ?? { label: log.action, cls: 'bg-gray-800 text-gray-400' };
                return (
                  <tr key={log.id} className="table-row">
                    <td><span className={`badge ${a.cls}`}>{a.label}</span></td>
                    <td><span className="text-gray-400 text-sm">{log.user_email || '—'}</span></td>
                    <td><span className="text-gray-500 text-sm">{log.details || '—'}</span></td>
                    <td><span className="text-gray-700 text-xs font-mono">{log.ip || '—'}</span></td>
                    <td>
                      <span className="text-gray-600 text-xs">
                        {new Date(log.created_at).toLocaleString('pt-BR', {
                          day: '2-digit', month: '2-digit', year: '2-digit',
                          hour: '2-digit', minute: '2-digit', second: '2-digit'
                        })}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
