'use client'

import { useEffect, useState } from 'react'
import api from '@/lib/api'

export default function AuditoriaPage() {
  const [logs, setLogs] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [pagination, setPagination] = useState({ page: 1, total: 0, totalPages: 1 })
  const [filters, setFilters] = useState({ userId: '', action: '', resource: '', startDate: '', endDate: '' })
  const [usuarios, setUsuarios] = useState<any[]>([])
  const [expanded, setExpanded] = useState<number | null>(null)

  useEffect(() => {
    // Users list for filter dropdown — only available to ADMIN so errors are expected if not ADMIN
    api.get('/users').then((r) => setUsuarios(r.data)).catch(() => {})
    fetchLogs()
  }, [])

  const fetchLogs = async (page = 1) => {
    setLoading(true)
    try {
      const r = await api.get('/audit', {
        params: {
          page,
          limit: 30,
          userId:    filters.userId    || undefined,
          action:    filters.action    || undefined,
          resource:  filters.resource  || undefined,
          startDate: filters.startDate || undefined,
          endDate:   filters.endDate   || undefined,
        },
      })
      setLogs(r.data.data)
      setPagination(r.data.pagination)
    } catch (e) {
      console.error(e)
    } finally {
      setLoading(false)
    }
  }

  const actionBadge = (action: string) => {
    const styles: Record<string, string> = {
      CREATE: 'bg-green-100 text-green-800',
      UPDATE: 'bg-blue-100 text-blue-800',
      DELETE: 'bg-red-100 text-red-800',
      LOGIN:  'bg-purple-100 text-purple-800',
    }
    return (
      <span className={`px-2 py-0.5 rounded-full text-xs font-bold ${styles[action] || 'bg-gray-100 text-black'}`}>
        {action}
      </span>
    )
  }

  const RESOURCES: Record<string, string> = {
    User:      'Usuario',
    Item:      'Artículo',
    Project:   'Proyecto',
    Warehouse: 'Bodega',
    Supplier:  'Proveedor',
    Ingreso:   'Ingreso',
    Salida:    'Salida',
    Kardex:    'Kardex',
  }

  const inputCls = 'border rounded-lg px-3 py-2 text-sm text-black focus:outline-none focus:ring-2 focus:ring-indigo-400'

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="bg-white rounded-xl shadow-sm border p-4">
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
          <div>
            <label className="block text-xs font-bold text-black mb-1">Usuario</label>
            <select className={inputCls + ' w-full'} value={filters.userId}
              onChange={(e) => setFilters({ ...filters, userId: e.target.value })}>
              <option value="">Todos</option>
              {usuarios.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-bold text-black mb-1">Acción</label>
            <select className={inputCls + ' w-full'} value={filters.action}
              onChange={(e) => setFilters({ ...filters, action: e.target.value })}>
              <option value="">Todas</option>
              {['CREATE', 'UPDATE', 'DELETE', 'LOGIN'].map((a) => (
                <option key={a} value={a}>{a}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-bold text-black mb-1">Recurso</label>
            <select className={inputCls + ' w-full'} value={filters.resource}
              onChange={(e) => setFilters({ ...filters, resource: e.target.value })}>
              <option value="">Todos</option>
              {Object.entries(RESOURCES).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-bold text-black mb-1">Desde</label>
            <input type="date" className={inputCls + ' w-full'} value={filters.startDate}
              onChange={(e) => setFilters({ ...filters, startDate: e.target.value })} />
          </div>
          <div>
            <label className="block text-xs font-bold text-black mb-1">Hasta</label>
            <input type="date" className={inputCls + ' w-full'} value={filters.endDate}
              onChange={(e) => setFilters({ ...filters, endDate: e.target.value })} />
          </div>
          <div className="flex items-end">
            <button onClick={() => fetchLogs(1)}
              className="w-full px-4 py-2 bg-indigo-600 text-white rounded-lg text-sm font-bold hover:bg-indigo-700 transition">
              🔍 Buscar
            </button>
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
        {!loading && (
          <div className="px-4 py-2 bg-gray-50 border-b text-xs font-semibold text-black">
            {pagination.total.toLocaleString()} registro(s)
          </div>
        )}
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead className="bg-gray-50 text-black text-xs font-bold uppercase">
              <tr>
                <th className="px-4 py-3 text-left">Fecha/Hora</th>
                <th className="px-4 py-3 text-left">Usuario</th>
                <th className="px-4 py-3 text-center">Acción</th>
                <th className="px-4 py-3 text-left">Recurso</th>
                <th className="px-4 py-3 text-left">ID</th>
                <th className="px-4 py-3 text-left">IP</th>
                <th className="px-4 py-3 text-center">Detalles</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {loading ? (
                <tr>
                  <td colSpan={7} className="text-center py-12">
                    <div className="flex items-center justify-center gap-2 text-black">
                      <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-indigo-600" />
                      Cargando...
                    </div>
                  </td>
                </tr>
              ) : logs.length === 0 ? (
                <tr>
                  <td colSpan={7} className="text-center py-12 text-black font-medium">
                    No hay registros de auditoría
                  </td>
                </tr>
              ) : logs.map((log) => (
                <>
                  <tr key={log.id} className="hover:bg-gray-50">
                    <td className="px-4 py-2 text-xs text-black font-medium whitespace-nowrap">
                      {new Date(log.createdAt).toLocaleString('es-HN')}
                    </td>
                    <td className="px-4 py-2 font-semibold text-black">
                      {log.user?.name || <span className="text-gray-400 italic">Sistema</span>}
                    </td>
                    <td className="px-4 py-2 text-center">{actionBadge(log.action)}</td>
                    <td className="px-4 py-2 font-medium text-black">
                      {RESOURCES[log.resource] || log.resource}
                    </td>
                    <td className="px-4 py-2 text-black">
                      {log.resourceId ? `#${log.resourceId}` : '—'}
                    </td>
                    <td className="px-4 py-2 font-mono text-xs text-black">
                      {log.ipAddress || '—'}
                    </td>
                    <td className="px-4 py-2 text-center">
                      {log.details && (
                        <button
                          onClick={() => setExpanded(expanded === log.id ? null : log.id)}
                          className="text-indigo-700 font-bold text-xs hover:underline"
                        >
                          {expanded === log.id ? 'Cerrar ▲' : 'Ver ▼'}
                        </button>
                      )}
                    </td>
                  </tr>
                  {expanded === log.id && log.details && (
                    <tr key={`${log.id}-detail`} className="bg-slate-50">
                      <td colSpan={7} className="px-6 py-3">
                        <pre className="text-xs text-black bg-white border rounded-lg p-3 overflow-x-auto max-h-48 font-mono">
                          {JSON.stringify(log.details, null, 2)}
                        </pre>
                      </td>
                    </tr>
                  )}
                </>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {pagination.totalPages > 1 && (
          <div className="flex justify-center items-center gap-4 py-4 border-t text-sm">
            <button
              disabled={pagination.page <= 1}
              onClick={() => fetchLogs(pagination.page - 1)}
              className="px-4 py-1.5 border rounded-lg font-semibold text-black disabled:opacity-40 hover:bg-gray-50 transition"
            >
              ← Anterior
            </button>
            <span className="font-semibold text-black">
              Página {pagination.page} de {pagination.totalPages}
            </span>
            <button
              disabled={pagination.page >= pagination.totalPages}
              onClick={() => fetchLogs(pagination.page + 1)}
              className="px-4 py-1.5 border rounded-lg font-semibold text-black disabled:opacity-40 hover:bg-gray-50 transition"
            >
              Siguiente →
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
