'use client'

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

type LogEntry = {
  id: number
  ip: string | null
  loginAt: string
  logoutAt: string | null
  user: { name: string; email: string; role: string }
}

const roleBadge: Record<string, string> = {
  SUPER_ADMIN: 'bg-red-100 text-red-700',
  ADMIN: 'bg-orange-100 text-orange-700',
  EDITOR: 'bg-blue-100 text-blue-700',
  GERENCIAL: 'bg-purple-100 text-purple-700',
  VISUALIZADOR: 'bg-gray-100 text-gray-600',
}

export default function AccesosPage() {
  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 [filterUser, setFilterUser] = useState('')
  const pageSize = 30

  const load = useCallback(async () => {
    setLoading(true)
    const params = new URLSearchParams({ page: String(page) })
    if (filterUser) params.set('userId', filterUser)
    const res = await fetch('/api/admin/accesos?' + params)
    const data = await res.json()
    setLogs(data.logs)
    setTotal(data.total)
    setUsers(data.users)
    setLoading(false)
  }, [page, filterUser])

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

  const totalPages = Math.ceil(total / pageSize)

  return (
    <div>
      <Header title="Historial de Accesos" />
      <div className="p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div>
            <label className="block text-xs text-gray-500 mb-1">Filtrar por usuario</label>
            <select
              value={filterUser}
              onChange={(e) => { setFilterUser(e.target.value); setPage(1) }}
              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 los usuarios</option>
              {users.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          </div>
        </div>

        <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">
            <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">Usuario</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Rol</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">IP</th>
                  <th className="text-left px-4 py-3 text-gray-500 font-medium">Inicio de sesión</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">
                      <p className="font-medium text-gray-800">{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 ${roleBadge[l.user.role] ?? 'bg-gray-100 text-gray-600'}`}>
                        {l.user.role}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-gray-500 text-xs font-mono">{l.ip ?? '—'}</td>
                    <td className="px-4 py-3 text-gray-500 text-xs">
                      {new Date(l.loginAt).toLocaleString('es-CL')}
                    </td>
                  </tr>
                ))}
                {logs.length === 0 && (
                  <tr>
                    <td colSpan={4} 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>
  )
}
