"use client";

import { useState, useEffect } from "react";
import { ShieldAlert, Loader2, Calendar, User, Info, Activity } from "lucide-react";

type AdminLog = {
  id: string;
  action: string;
  details: string | null;
  ipAddress: string | null;
  createdAt: string;
  user: { name: string; email: string };
};

export default function AdminLogsClient() {
  const [logs, setLogs] = useState<AdminLog[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchLogs();
  }, []);

  const fetchLogs = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/logs?limit=50");
      const data = await res.json();
      if (data.logs) setLogs(data.logs);
    } catch (e) {
      console.error(e);
      alert("Error cargando los logs");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <ShieldAlert className="text-red-500 w-7 h-7" />
          <h1 className="text-3xl font-bold">Registro de Auditoría</h1>
        </div>
      </div>

      <p className="text-gray-400 text-sm border-l-4 border-red-500 pl-4 py-1">
        Este registro técnico es inmutable. Cada acción importante dentro de la plataforma es grabada aquí para asegurar trazabilidad. 
        Muestra las últimas 50 operaciones (modo descendente).
      </p>

      {loading ? (
        <div className="flex justify-center items-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-gray-500" />
        </div>
      ) : (
        <div className="overflow-x-auto rounded-xl border border-white/10 shadow-lg">
          <table className="w-full text-left text-sm text-gray-400 bg-black/20">
            <thead className="text-xs text-gray-300 uppercase bg-black/40 border-b border-white/10">
              <tr>
                <th className="px-6 py-4 flex items-center gap-2 font-medium">
                  <Calendar className="w-4 h-4 text-neon-blue" /> Fecha y Hora
                </th>
                <th className="px-6 py-4 font-medium">
                  <span className="flex items-center gap-2"><User className="w-4 h-4 text-neon-purple" /> Administrador</span>
                </th>
                <th className="px-6 py-4 font-medium">
                  <span className="flex items-center gap-2"><Activity className="w-4 h-4 text-[#39ff14]" /> Acción Ejecutada</span>
                </th>
                <th className="px-6 py-4 font-medium">
                  <span className="flex items-center gap-2"><Info className="w-4 h-4 text-gray-400" /> Detalles Opcionales</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => (
                <tr key={log.id} className="border-b border-white/5 hover:bg-white/5 transition-colors">
                  <td className="px-6 py-4 whitespace-nowrap text-gray-200">
                    {new Date(log.createdAt).toLocaleString("es-CL")}
                  </td>
                  <td className="px-6 py-4">
                    <div className="font-semibold text-gray-200">{log.user?.name || "Desconocido"}</div>
                    <div className="text-xs text-gray-500">{log.user?.email}</div>
                  </td>
                  <td className="px-6 py-4">
                    <span className="px-3 py-1 bg-red-500/10 text-red-400 rounded-lg text-xs font-bold font-mono border border-red-500/20">
                      {log.action}
                    </span>
                  </td>
                  <td className="px-6 py-4 font-mono text-xs text-gray-500 truncate max-w-xs" title={log.details || ""}>
                    {log.details || "-"}
                  </td>
                </tr>
              ))}
              {logs.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-6 py-8 text-center text-gray-500">
                    Sin registros todavía.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
