"use client";

import { useCallback, useEffect, useState } from "react";
import { AlertTriangle, ChevronDown, RefreshCw } from "lucide-react";

interface LogEntry { id: string; level: string; source: string; message: string; endpoint: string | null; details: unknown; timestamp: string }

export default function AdminErrors() {
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [source, setSource] = useState("");
  const [expanded, setExpanded] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch(`/api/admin/errors?limit=100${source ? `&source=${source}` : ""}`);
    if (res.ok) { const d = await res.json(); setLogs(d.errors ?? []); }
    setLoading(false);
  }, [source]);
  useEffect(() => { load(); const id = setInterval(load, 30000); return () => clearInterval(id); }, [load]);

  return (
    <div className="space-y-6 max-w-6xl">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-slate-900">Error Log</h1>
        <div className="flex items-center gap-2">
          <select value={source} onChange={(e) => setSource(e.target.value)} className="text-xs border border-slate-200 rounded-lg px-3 py-2 bg-white">
            <option value="">All sources</option>
            {["api_route", "cron", "sync", "ai_call", "site_tag"].map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
          <button onClick={load} className="flex items-center gap-1 px-3 py-2 rounded-lg border border-slate-200 text-xs font-semibold text-slate-600 hover:bg-slate-50"><RefreshCw className="w-3 h-3" /> Refresh</button>
        </div>
      </div>

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        {loading ? <div className="px-5 py-12 text-center text-slate-400">Loading...</div> :
        logs.length === 0 ? <div className="px-5 py-12 text-center text-slate-400">No errors found.</div> :
        <div className="divide-y divide-slate-100">
          {logs.map((l) => (
            <div key={l.id}>
              <button onClick={() => setExpanded(expanded === l.id ? null : l.id)} className="w-full flex items-center gap-3 px-5 py-3 text-left hover:bg-slate-50">
                <span className={`w-2 h-2 rounded-full shrink-0 ${l.level === "error" ? "bg-red-500" : "bg-amber-400"}`} />
                <span className="text-[10px] text-slate-400 w-24 shrink-0 tabular-nums">{new Date(l.timestamp).toLocaleString("en-US", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })}</span>
                <span className="text-[10px] font-bold text-slate-500 w-16 shrink-0">{l.source}</span>
                {l.endpoint && <span className="text-[10px] font-mono text-slate-400 w-32 shrink-0 truncate">{l.endpoint}</span>}
                <span className="text-xs text-slate-700 flex-1 truncate">{l.message}</span>
                <ChevronDown className={`w-3.5 h-3.5 text-slate-400 shrink-0 transition-transform ${expanded === l.id ? "rotate-180" : ""}`} />
              </button>
              {expanded === l.id && l.details != null && (
                <div className="px-5 pb-3 pl-14"><pre className="text-[11px] text-slate-600 bg-slate-50 rounded-lg p-3 overflow-x-auto whitespace-pre-wrap">{String(JSON.stringify(l.details, null, 2))}</pre></div>
              )}
            </div>
          ))}
        </div>}
      </div>
    </div>
  );
}
