// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotDiagnostics.tsx
// @Desc: Browse/filter the uptime_api_logs table to diagnose UptimeRobot
//        connectivity issues, rate-limits and validation failures.
import { useCallback, useEffect, useState } from "react";
import {
  FileSearch,
  Loader2,
  RefreshCw,
  CheckCircle2,
  XCircle,
} from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, Select } from "../ui";
import {
  adminListApiLogs,
  type UptimeApiLogItem,
} from "@/lib/uptimerobotApi";

const PAGE_SIZE = 50;

export default function CmsUptimeRobotDiagnostics() {
  const [items, setItems] = useState<UptimeApiLogItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState("");
  const [q, setQ] = useState("");
  const [offset, setOffset] = useState(0);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await adminListApiLogs({
        limit: PAGE_SIZE,
        offset,
        status: status || undefined,
        q: q || undefined,
      });
      setItems(res.items);
      setTotal(res.total);
    } catch (e) {
      toast.error(`Load failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setLoading(false);
    }
  }, [status, q, offset]);

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

  const nextPage = () => setOffset(offset + PAGE_SIZE);
  const prevPage = () => setOffset(Math.max(0, offset - PAGE_SIZE));

  return (
    <CmsLayout>
      <PageHeader
        title="Diagnostics"
        description="Browse every outbound UptimeRobot API call, including latency and error class."
        icon={<FileSearch className="w-6 h-6" />}
      />

      <SectionCard
        title="API call logs"
        description={`${total} total log entries. Showing ${items.length} from offset ${offset}.`}
        actions={
          <button
            onClick={load}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold"
          >
            <RefreshCw className="w-4 h-4" />
            Refresh
          </button>
        }
      >
        <div className="flex flex-wrap items-end gap-3 pb-3 border-b border-slate-100">
          <div className="min-w-[160px]">
            <Field label="Status">
              <Select
                value={status}
                onChange={(e) => {
                  setStatus(e.target.value);
                  setOffset(0);
                }}
              >
                <option value="">All</option>
                <option value="ok">OK</option>
                <option value="error">Error</option>
              </Select>
            </Field>
          </div>
          <div className="flex-1 min-w-[240px]">
            <Field label="Search (endpoint / email / error)">
              <TextInput
                value={q}
                onChange={(e) => setQ(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    setOffset(0);
                    load();
                  }
                }}
                placeholder="/monitors or error class name"
              />
            </Field>
          </div>
          <button
            onClick={() => {
              setOffset(0);
              load();
            }}
            className="px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#095a32]"
          >
            Apply
          </button>
        </div>

        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm pt-4">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : items.length === 0 ? (
          <div className="text-sm text-slate-500 pt-4">No log entries found.</div>
        ) : (
          <div className="overflow-x-auto pt-3">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs uppercase text-slate-500 border-b border-slate-200">
                  <th className="py-2 pr-4">When</th>
                  <th className="py-2 pr-4">Status</th>
                  <th className="py-2 pr-4">Method</th>
                  <th className="py-2 pr-4">Endpoint</th>
                  <th className="py-2 pr-4">HTTP</th>
                  <th className="py-2 pr-4">Latency</th>
                  <th className="py-2 pr-4">Actor</th>
                  <th className="py-2 pr-4">Error</th>
                </tr>
              </thead>
              <tbody>
                {items.map((row) => (
                  <tr key={row.id} className="border-b border-slate-100 align-top">
                    <td className="py-2 pr-4 text-xs text-slate-600 whitespace-nowrap">
                      {new Date(row.created_at).toLocaleString()}
                    </td>
                    <td className="py-2 pr-4">
                      {row.status === "ok" ? (
                        <span className="inline-flex items-center gap-1 text-emerald-700 text-xs font-bold">
                          <CheckCircle2 className="w-3.5 h-3.5" /> OK
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-red-700 text-xs font-bold">
                          <XCircle className="w-3.5 h-3.5" /> ERROR
                        </span>
                      )}
                    </td>
                    <td className="py-2 pr-4 font-mono text-xs text-slate-700">
                      {row.method}
                    </td>
                    <td className="py-2 pr-4 font-mono text-xs text-slate-700 break-all">
                      {row.endpoint}
                    </td>
                    <td className="py-2 pr-4 text-xs">{row.http_status ?? "—"}</td>
                    <td className="py-2 pr-4 text-xs">
                      {row.duration_ms !== null ? `${row.duration_ms}ms` : "—"}
                    </td>
                    <td className="py-2 pr-4 text-xs text-slate-600 break-all">
                      {row.user_email ?? "—"}
                    </td>
                    <td className="py-2 pr-4 text-xs text-red-700 max-w-[360px]">
                      {row.error_class && (
                        <div className="font-bold">{row.error_class}</div>
                      )}
                      {row.error_message && (
                        <div className="text-slate-600 break-words">
                          {row.error_message}
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <div className="flex items-center justify-between pt-3">
          <button
            onClick={prevPage}
            disabled={offset === 0}
            className="px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold disabled:opacity-50"
          >
            ← Prev
          </button>
          <div className="text-xs text-slate-500">
            Page {Math.floor(offset / PAGE_SIZE) + 1} of{" "}
            {Math.max(1, Math.ceil(total / PAGE_SIZE))}
          </div>
          <button
            onClick={nextPage}
            disabled={offset + PAGE_SIZE >= total}
            className="px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold disabled:opacity-50"
          >
            Next →
          </button>
        </div>
      </SectionCard>
    </CmsLayout>
  );
}