'use client'

import { useState, useEffect, useCallback } from 'react'
import Header from '@/components/layout/Header'
import { FunnelIcon, ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/24/outline'

type LogEntry = {
  id: number
  action: string
  entity: string
  entityId: number | null
  details: string | null
  createdAt: string
  user: { name: string; email: string }
}

const actionColor: Record<string, string> = {
  LOGIN: 'bg-blue-100 text-blue-700',
  UPDATE_USER: 'bg-yellow-100 text-yellow-700',
  UPDATE_MENU_CONFIG: 'bg-purple-100 text-purple-700',
}

export default function AuditoriaPage() {
  const [logs, setLogs] = useState<LogEntry[]>([])
  const [users, setUsers] = useState<{ id: number; name: string }[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({ userId: '', action: '', desde: '', hasta: '' })
  const pageSize = 25

  const load = useCallback(async () => {
    setLoading(true)
    const params = new URLSearchParams({ page: String(page) })
    if (filters.userId) params.set('userId', filters.userId)
    if (filters.action) params.set('action', filters.action)
    if (filters.desde) params.set('desde', filters.desde)
    if (filters.hasta) params.set('hasta', filters.hasta)

    const res = await fetch('/api/admin/auditoria?' + params)
    const data = await res.json()
    setLogs(data.logs)
    setTotal(data.total)
    setUsers(data.users)
    setLoading(false)
  }, [page, filters])

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

  function applyFilters(e: React.FormEvent) {
    e.preventDefault()
    setPage(1)
    load()
  }

  const totalPages = Math.ceil(total / pageSize)

  return (
    <div>
      <Header title="Auditoría" />
      <div className="p-6 space-y-4">
        <form onSubmit={applyFilters} className="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
          <div className="flex flex-wrap gap-3 items-end">
            <div>
              <label className="block text-xs text-gray-500 mb-1">Usuario</label>
              <select
                value={filters.userId}
                onChange={(e) => setFilters((f) => ({ ...f, userId: e.target.value }))}
                className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
              >
                <option value="">Todos</option>
                {users.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Acción</label>
              <input
                type="text"
                placeholder="ej. LOGIN"
                value={filters.action}
                onChange={(e) => setFilters((f) => ({ ...f, action: e.target.value }))}
                className="border border-gray-200 rounded-lg px-3 py-2 text-sm w-36 outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Desde</label>
              <input
                type="date"
                value={filters.desde}
                onChange={(e) => setFilters((f) => ({ ...f, desde: e.target.value }))}
                className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Hasta</label>
              <input
                type="date"
                value={filters.hasta}
                onChange={(e) => setFilters((f) => ({ ...f, hasta: e.target.value }))}
                className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-green-500"
              />
            </div>
            <button
              type="submit"
              className="flex items-center gap-1.5 px-4 py-2 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700"
            >
              <FunnelIcon className="w-4 h-4" />
              Filtrar
            </button>
            <button
              type="button"
              onClick={() => { setFilters({ userId: '', action: '', desde: '', hasta: '' }); setPage(1) }}
              className="px-4 py-2 text-sm text-gray-500 hover:text-gray-700 rounded-lg"
            >
              Limpiar
            </button>
          </div>
        </form>

        <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-4 py-3 border-b border-gray-50 flex items-center justify-between">
            <span className="text-xs text-gray-400">{total} registro(s)</span>
          </div>
          {loading ? (
            <p className="text-gray-400 text-sm p-6">Cargando...</p>
          ) : (
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-100">
                <tr>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Fecha</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Usuario</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Acción</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Entidad</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Detalles</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {logs.map((l) => (
                  <tr key={l.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
                      {new Date(l.createdAt).toLocaleString('es-CL')}
                    </td>
                    <td className="px-4 py-3">
                      <p className="text-gray-800 text-xs font-medium">{l.user.name}</p>
                      <p className="text-gray-400 text-xs">{l.user.email}</p>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${actionColor[l.action] ?? 'bg-gray-100 text-gray-600'}`}>
                        {l.action}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-600 text-xs">{l.entity}</td>
                    <td className="px-4 py-3 text-gray-400 text-xs max-w-xs truncate">{l.details ?? '—'}</td>
                  </tr>
                ))}
                {logs.length === 0 && (
                  <tr>
                    <td colSpan={5} className="text-center py-8 text-gray-400 text-sm">Sin registros</td>
                  </tr>
                )}
              </tbody>
            </table>
          )}

          {totalPages > 1 && (
            <div className="px-4 py-3 border-t border-gray-50 flex items-center justify-between">
              <span className="text-xs text-gray-400">Pág. {page} de {totalPages}</span>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className="p-1 rounded hover:bg-gray-100 disabled:opacity-40"
                >
                  <ChevronLeftIcon className="w-4 h-4 text-gray-600" />
                </button>
                <button
                  onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                  disabled={page === totalPages}
                  className="p-1 rounded hover:bg-gray-100 disabled:opacity-40"
                >
                  <ChevronRightIcon className="w-4 h-4 text-gray-600" />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
