"use client";

import { useCallback, useEffect, useState } from "react";
import { ApiError, apiGet } from "@/lib/api";
import { formatWhen } from "@/lib/online-class-labels";
import {
  clearOnlineClassApiErrors,
  readOnlineClassApiErrors,
  type OnlineClassApiErrorEntry,
} from "@/lib/online-class-api-log";
import { Button } from "@/components/ui/Button";

type ProviderCall = {
  id: number;
  operation: string;
  status: string;
  attempt: number;
  error_code?: string | null;
  error_message?: string | null;
  request_summary?: unknown;
  response_summary?: unknown;
  related_type?: string | null;
  related_id?: number | null;
  created_at?: string | null;
  provider?: { title?: string; driver_key?: string } | null;
};

const STATUS_LABEL: Record<string, string> = {
  failed: "ناموفق",
  dead: "متوقف",
  retrying: "در انتظار تلاش دوباره",
  pending: "در حال انجام",
  success: "موفق",
};

export function ApiErrorLog() {
  const [calls, setCalls] = useState<ProviderCall[]>([]);
  const [browserErrors, setBrowserErrors] = useState<OnlineClassApiErrorEntry[]>([]);
  const [openId, setOpenId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [forbidden, setForbidden] = useState(false);

  const loadBrowser = useCallback(() => {
    setBrowserErrors(readOnlineClassApiErrors());
  }, []);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    loadBrowser();
    try {
      const rows = await apiGet<ProviderCall[]>("/online-class/provider-calls?limit=40");
      setCalls(Array.isArray(rows) ? rows : []);
      setForbidden(false);
    } catch (err) {
      if (err instanceof ApiError && err.status === 403) {
        setForbidden(true);
        setCalls([]);
      } else {
        setError(err instanceof ApiError ? err.message : "لاگ خطاها بارگذاری نشد.");
      }
    } finally {
      setLoading(false);
    }
  }, [loadBrowser]);

  useEffect(() => {
    load();
    const onBrowser = () => loadBrowser();
    window.addEventListener("online-class-api-error", onBrowser);
    return () => window.removeEventListener("online-class-api-error", onBrowser);
  }, [load, loadBrowser]);

  const copyText = async (value: unknown) => {
    try {
      await navigator.clipboard.writeText(JSON.stringify(value, null, 2));
    } catch {
      setError("کپی در کلیپ‌بورد انجام نشد.");
    }
  };

  return (
    <section className="mt-4 overflow-hidden rounded-2xl border border-[var(--border)] bg-white shadow-card">
      <div className="flex flex-wrap items-center gap-2 border-b border-[var(--border)] px-4 py-3">
        <div className="min-w-0 flex-1">
          <h2 className="text-sm font-bold">لاگ خطاهای API کلاس آنلاین</h2>
          <p className="mt-0.5 text-xs text-[var(--muted)]">
            پاسخ کامل درخواست‌های پنل و جزئیات تماس سرور با ادوبی، اسکای‌روم، الوکام و فنوتک
          </p>
        </div>
        <Button type="button" variant="secondary" onClick={() => load()}>
          بروزرسانی
        </Button>
        <Button
          type="button"
          variant="secondary"
          onClick={() => {
            clearOnlineClassApiErrors();
            loadBrowser();
          }}
        >
          پاک کردن لاگ مرورگر
        </Button>
      </div>

      <div className="space-y-4 p-4">
        {error ? <p className="text-sm text-red-700">{error}</p> : null}
        {loading ? <p className="text-sm text-[var(--muted)]">در حال بارگذاری لاگ…</p> : null}

        <div>
          <h3 className="mb-2 text-xs font-bold text-[var(--muted)]">درخواست‌های این مرورگر به API</h3>
          {browserErrors.length === 0 ? (
            <p className="text-sm text-[var(--muted)]">خطای تازه‌ای از درخواست‌های پنل ثبت نشده است.</p>
          ) : (
            <ul className="space-y-2">
              {browserErrors.map((entry) => {
                const key = `browser-${entry.id}`;
                const open = openId === key;
                return (
                  <li key={entry.id} className="rounded-xl border border-red-100 bg-red-50/60">
                    <button
                      type="button"
                      className="flex w-full items-start gap-2 px-3 py-2 text-right"
                      onClick={() => setOpenId(open ? null : key)}
                    >
                      <span className="shrink-0 rounded bg-red-100 px-1.5 py-0.5 text-[11px] font-semibold text-red-800">
                        {entry.status || "شبکه"}
                      </span>
                      <span className="min-w-0 flex-1">
                        <span className="block text-xs font-semibold">
                          {entry.method} {entry.path}
                        </span>
                        <span className="mt-0.5 block text-xs text-red-800">{entry.message}</span>
                        <span className="mt-0.5 block text-[11px] text-[var(--muted)]">{formatWhen(entry.at)}</span>
                      </span>
                    </button>
                    {open ? (
                      <LogBody
                        value={{ status: entry.status, message: entry.message, payload: entry.payload }}
                        onCopy={() => copyText(entry)}
                      />
                    ) : null}
                  </li>
                );
              })}
            </ul>
          )}
        </div>

        {forbidden ? null : (
          <div>
            <h3 className="mb-2 text-xs font-bold text-[var(--muted)]">تماس سرور با سرویس کلاس</h3>
            {!loading && calls.length === 0 ? (
              <p className="text-sm text-[var(--muted)]">خطای ذخیره‌شده‌ای از سرویس‌های کلاس آنلاین نیست.</p>
            ) : (
              <ul className="space-y-2">
                {calls.map((call) => {
                  const key = `call-${call.id}`;
                  const open = openId === key;
                  return (
                    <li key={call.id} className="rounded-xl border border-[var(--border)]">
                      <button
                        type="button"
                        className="flex w-full items-start gap-2 px-3 py-2 text-right"
                        onClick={() => setOpenId(open ? null : key)}
                      >
                        <span className="shrink-0 rounded bg-slate-100 px-1.5 py-0.5 text-[11px] font-semibold text-slate-700">
                          {STATUS_LABEL[call.status] ?? call.status}
                        </span>
                        <span className="min-w-0 flex-1">
                          <span className="block text-xs font-semibold">
                            {call.provider?.title ?? "سرور نامشخص"} · {call.operation}
                          </span>
                          <span className="mt-0.5 block text-xs text-red-800">
                            {call.error_code ? `${call.error_code}: ` : ""}
                            {call.error_message || "بدون پیام"}
                          </span>
                          <span className="mt-0.5 block text-[11px] text-[var(--muted)]">
                            {formatWhen(call.created_at)} · تلاش {call.attempt}
                            {call.related_id ? ` · ${call.related_type ?? "مربوط"} #${call.related_id}` : ""}
                          </span>
                        </span>
                      </button>
                      {open ? (
                        <LogBody
                          value={{
                            error_code: call.error_code,
                            error_message: call.error_message,
                            request: call.request_summary,
                            response: call.response_summary,
                          }}
                          onCopy={() => copyText(call)}
                        />
                      ) : null}
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
        )}
      </div>
    </section>
  );
}

function LogBody({ value, onCopy }: { value: unknown; onCopy: () => void }) {
  return (
    <div className="border-t border-[var(--border)] px-3 py-2">
      <div className="mb-2 flex justify-end">
        <button type="button" className="text-xs font-medium text-[var(--primary)]" onClick={onCopy}>
          کپی JSON
        </button>
      </div>
      <pre className="max-h-80 overflow-auto whitespace-pre-wrap break-all rounded-lg bg-slate-950 p-3 text-left text-[11px] leading-5 text-slate-100" dir="ltr">
        {JSON.stringify(value, null, 2)}
      </pre>
    </div>
  );
}
