"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { LuCheck, LuChevronDown, LuChevronLeft, LuChevronRight, LuChevronUp, LuCircleAlert, LuClock3, LuHistory, LuRefreshCw, LuSearch } from "react-icons/lu";

type HistoryFile = { id: string; fileName: string; pageNumber: number; status: "EXTRACTED" | "FAILED" | "SAVED"; errorMessage: string | null };
type HistoryEvent = { id: string; type: string; message: string; createdAt: string };
type HistorySession = { id: string; folderPath: string; status: "ACTIVE" | "PROCESSING" | "COMPLETED" | "FAILED"; startedAt: string; finishedAt: string | null; category: { name: string; icon: string | null }; user: { name: string | null; username: string } ; files: HistoryFile[]; events: HistoryEvent[] };

const LOG_PAGE_SIZE = 6;

function LogDetailsTable({ events }: { events: HistoryEvent[] }) {
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const normalizedSearch = search.trim().toLowerCase();
  const filteredEvents = events.filter((event) => `${event.message} ${event.type} ${event.createdAt}`.toLowerCase().includes(normalizedSearch));
  const totalPages = Math.max(1, Math.ceil(filteredEvents.length / LOG_PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const visibleEvents = filteredEvents.slice((currentPage - 1) * LOG_PAGE_SIZE, currentPage * LOG_PAGE_SIZE);

  const changeSearch = (value: string) => {
    setSearch(value);
    setPage(1);
  };

  return <div className="space-y-3">
    <div className="relative">
      <LuSearch className="absolute left-3 top-1/2 -translate-y-1/2 text-text-subtle" aria-hidden="true" />
      <input type="search" value={search} onChange={(event) => changeSearch(event.target.value)} placeholder="Buscar en el log…" aria-label="Buscar en el log" className="w-full pl-9 pr-3 py-2 rounded-lg border border-border-subtle bg-background text-sm focus:border-primary focus:ring-1 focus:ring-primary" />
    </div>
    {visibleEvents.length === 0 ? <p className="p-4 rounded-lg border border-dashed border-border-subtle text-sm text-text-muted text-center">{events.length ? "No hay eventos que coincidan con la búsqueda." : "Sin eventos."}</p> : <div className="rounded-lg border border-border-subtle overflow-auto max-h-96">
      <table className="w-full min-w-[540px] text-sm text-left">
        <thead className="sticky top-0 bg-background-alt text-xs uppercase text-text-muted">
          <tr><th scope="col" className="px-3 py-2.5 font-semibold">Mensaje</th><th scope="col" className="px-3 py-2.5 font-semibold whitespace-nowrap">Tipo</th><th scope="col" className="px-3 py-2.5 font-semibold whitespace-nowrap">Fecha</th></tr>
        </thead>
        <tbody className="divide-y divide-border-light">
          {visibleEvents.map((event) => <tr key={event.id} className="align-top hover:bg-background-alt/50"><td className="px-3 py-3 text-text">{event.message}</td><td className="px-3 py-3 text-xs text-text-muted whitespace-nowrap">{event.type}</td><td className="px-3 py-3 text-xs text-text-muted whitespace-nowrap">{new Date(event.createdAt).toLocaleString()}</td></tr>)}
        </tbody>
      </table>
    </div>}
    <div className="flex items-center justify-between gap-3 text-xs text-text-muted">
      <span>{filteredEvents.length} evento(s){search.trim() ? " encontrados" : ""}</span>
      {filteredEvents.length > 0 && <div className="flex items-center gap-2"><span>Página {currentPage} de {totalPages}</span><button type="button" onClick={() => setPage((value) => Math.max(1, value - 1))} disabled={currentPage === 1} aria-label="Página anterior" className="p-1.5 rounded-md border border-border-subtle hover:bg-background-alt disabled:opacity-40"><LuChevronLeft /></button><button type="button" onClick={() => setPage((value) => Math.min(totalPages, value + 1))} disabled={currentPage === totalPages} aria-label="Página siguiente" className="p-1.5 rounded-md border border-border-subtle hover:bg-background-alt disabled:opacity-40"><LuChevronRight /></button></div>}
    </div>
  </div>;
}

export default function ScannerHistoryPage() {
  const { status } = useSession();
  const router = useRouter();
  const [sessions, setSessions] = useState<HistorySession[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expanded, setExpanded] = useState<string | null>(null);

  const loadHistory = async () => {
    setLoading(true); setError(null);
    try {
      const response = await fetch("/api/scanner/sharepoint/history");
      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "No se pudo cargar el historial.");
      setSessions(data.sessions);
    } catch (loadError) { setError(loadError instanceof Error ? loadError.message : "No se pudo cargar el historial."); }
    finally { setLoading(false); }
  };

  useEffect(() => { if (status === "authenticated") void loadHistory(); }, [status]);
  if (status === "unauthenticated") { router.replace("/login"); return null; }

  return <div className="max-w-6xl mx-auto space-y-6">
    <div className="flex items-center justify-between gap-4"><h1 className="text-2xl md:text-3xl font-bold text-text flex items-center gap-3"><LuHistory className="text-primary" /> Historial de escáner</h1><button onClick={loadHistory} disabled={loading} className="px-4 py-2 rounded-lg border border-border-subtle text-sm font-semibold flex items-center gap-2 hover:bg-background-alt disabled:opacity-50"><LuRefreshCw className={loading ? "animate-spin" : ""} />Actualizar</button></div>
    {error && <div className="p-4 rounded-xl bg-destructive-background border border-destructive-border text-destructive-foreground">{error}</div>}
    {loading ? <p className="text-text-muted">Cargando historial…</p> : sessions.length === 0 ? <div className="p-10 border border-dashed border-border-subtle rounded-2xl text-center text-text-muted">Aún no hay sesiones de escáner registradas.</div> : <div className="space-y-4">{sessions.map((session) => {
      const failedFiles = session.files.filter((file) => file.status === "FAILED");
      const successFiles = session.files.filter((file) => file.status === "EXTRACTED" || file.status === "SAVED");
      const isOpen = expanded === session.id;
      return <article key={session.id} className="bg-background border border-border-subtle rounded-2xl overflow-hidden"><button type="button" onClick={() => setExpanded(isOpen ? null : session.id)} className="w-full p-5 text-left flex flex-col md:flex-row md:items-center gap-4 justify-between hover:bg-background-alt/50"><div><div className="flex items-center gap-2"><span className={`text-xs font-bold px-2.5 py-1 rounded-full ${failedFiles.length || session.status === "FAILED" ? "bg-destructive-background text-destructive-foreground" : "bg-success-background text-success-foreground"}`}>{failedFiles.length || session.status === "FAILED" ? "Con fallos" : "Exitosa"}</span><span className="text-sm text-text-muted">{session.category.icon} {session.category.name}</span></div><h2 className="font-semibold mt-2">{session.folderPath}</h2><p className="text-xs text-text-muted mt-1 flex items-center gap-1"><LuClock3 />{new Date(session.startedAt).toLocaleString()} · {successFiles.length} procesado(s) · {failedFiles.length} fallido(s)</p></div>{isOpen ? <LuChevronUp /> : <LuChevronDown />}</button>{isOpen && <div className="border-t border-border-subtle p-5 grid lg:grid-cols-2 gap-6"><div><h3 className="font-semibold mb-3">Archivos procesados</h3>{session.files.length === 0 ? <p className="text-sm text-text-muted">Sin archivos procesados.</p> : <div className="space-y-2">{session.files.map((file) => <div key={file.id} className={`p-3 rounded-lg border ${file.status === "FAILED" ? "border-destructive-border bg-destructive-background" : "border-border-subtle"}`}><div className="flex gap-2 items-start"><span className={file.status === "FAILED" ? "text-destructive-foreground" : "text-success"}>{file.status === "FAILED" ? <LuCircleAlert /> : <LuCheck />}</span><div><p className="text-sm font-medium">{file.fileName}</p><p className="text-xs text-text-muted">Página {file.pageNumber} · {file.status === "SAVED" ? "Guardado" : file.status === "EXTRACTED" ? "Extraído" : "Fallido"}</p>{file.errorMessage && <p className="text-xs text-destructive-foreground mt-2 break-words">Error: {file.errorMessage}</p>}</div></div></div>)}</div>}</div><div><h3 className="font-semibold mb-3">Log / detalle</h3><LogDetailsTable key={session.id} events={session.events} /></div></div>}</article>;
    })}</div>}
  </div>;
}
