import { useState, useEffect } from 'react'
import { Shield, Loader2, Download, Search, FileText, AlertTriangle, CheckCircle } from 'lucide-react'
import api from '../services/api'

interface AuditLog {
  id: number
  timestamp: string
  usuario: string
  entidade: string
  acao: string
  detalhes: string
}

interface ComplianceReport {
  total_logs: number
  acoes_criticas: number
  usuarios_ativos: number
  entidades_auditadas: number
}

export default function Auditoria() {
  const [loading, setLoading] = useState(true)
  const [logs, setLogs] = useState<AuditLog[]>([])
  const [compliance, setCompliance] = useState<ComplianceReport | null>(null)
  const [entity, setEntity] = useState('')
  const [action, setAction] = useState('')
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')

  useEffect(() => { fetchData() }, [entity, action, dateFrom, dateTo])

  const fetchData = async () => {
    setLoading(true)
    try {
      const params: any = {}
      if (entity) params.entity = entity
      if (action) params.action = action
      if (dateFrom) params.date_from = dateFrom
      if (dateTo) params.date_to = dateTo
      const [logsRes, compRes] = await Promise.all([
        api.get('/audit/logs', { params }),
        api.get('/audit/compliance-report')
      ])
      setLogs(logsRes.data?.logs || logsRes.data || [])
      setCompliance(compRes.data)
    } catch (err) {
      console.error('Error fetching audit data:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleExport = (format: string) => {
    const token = localStorage.getItem('token')
    window.open(`/api/audit/export?format=${format}&token=${token}`, '_blank')
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    )
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-text flex items-center gap-2">
            <Shield className="w-8 h-8 text-secondary" /> Auditoria & Compliance
          </h1>
          <p className="text-gray mt-1">Registro de ações e conformidade do sistema.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => handleExport('csv')} className="btn-outline text-sm flex items-center gap-1">
            <Download className="w-4 h-4" /> CSV
          </button>
          <button onClick={() => handleExport('json')} className="btn-outline text-sm flex items-center gap-1">
            <Download className="w-4 h-4" /> JSON
          </button>
        </div>
      </div>

      {/* Compliance Summary */}
      {compliance && (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { title: 'Total de Logs', value: compliance.total_logs, icon: <FileText className="w-5 h-5" />, color: 'from-blue-500 to-blue-600' },
            { title: 'Ações Críticas', value: compliance.acoes_criticas, icon: <AlertTriangle className="w-5 h-5" />, color: 'from-red-500 to-red-600' },
            { title: 'Usuários Ativos', value: compliance.usuarios_ativos, icon: <CheckCircle className="w-5 h-5" />, color: 'from-green-500 to-green-600' },
            { title: 'Entidades Auditadas', value: compliance.entidades_auditadas, icon: <Shield className="w-5 h-5" />, color: 'from-purple-500 to-purple-600' },
          ].map((c, i) => (
            <div key={i} className="card">
              <div className={`w-10 h-10 rounded-xl bg-gradient-to-br ${c.color} flex items-center justify-center text-white mb-3`}>
                {c.icon}
              </div>
              <p className="text-sm text-gray">{c.title}</p>
              <p className="text-2xl font-bold text-text">{c.value}</p>
            </div>
          ))}
        </div>
      )}

      {/* Filters */}
      <div className="card">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
          <input type="text" placeholder="Filtrar entidade..." value={entity} onChange={e => setEntity(e.target.value)} className="input-field text-sm" />
          <input type="text" placeholder="Filtrar ação..." value={action} onChange={e => setAction(e.target.value)} className="input-field text-sm" />
          <input type="date" value={dateFrom} onChange={e => setDateFrom(e.target.value)} className="input-field text-sm" />
          <input type="date" value={dateTo} onChange={e => setDateTo(e.target.value)} className="input-field text-sm" />
        </div>
      </div>

      {/* Logs Table */}
      <div className="card overflow-x-auto">
        {Array.isArray(logs) && logs.length > 0 ? (
          <table className="w-full">
            <thead>
              <tr className="table-header">
                <th className="table-cell text-left">Timestamp</th>
                <th className="table-cell text-left">Usuário</th>
                <th className="table-cell text-left">Entidade</th>
                <th className="table-cell text-left">Ação</th>
                <th className="table-cell text-left">Detalhes</th>
              </tr>
            </thead>
            <tbody>
              {logs.map(log => (
                <tr key={log.id} className="table-row">
                  <td className="table-cell text-sm">{new Date(log.timestamp).toLocaleString('pt-BR')}</td>
                  <td className="table-cell text-sm font-medium">{log.usuario}</td>
                  <td className="table-cell text-sm">{log.entidade}</td>
                  <td className="table-cell">
                    <span className={`text-xs px-2 py-1 rounded-full ${
                      log.acao === 'DELETE' ? 'badge-error' :
                      log.acao === 'CREATE' ? 'badge-success' :
                      log.acao === 'UPDATE' ? 'badge-warning' : 'badge-info'
                    }`}>{log.acao}</span>
                  </td>
                  <td className="table-cell text-sm text-gray max-w-xs truncate">{log.detalhes}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="text-center py-12">
            <Search className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray">Nenhum log encontrado</h3>
            <p className="text-sm text-gray-light mt-1">Ajuste os filtros para visualizar registros de auditoria.</p>
          </div>
        )}
      </div>
    </div>
  )
}
