// @File: src/pages/admin/cms/CmsSyncDiagnostics.tsx
// @Desc: Cross-module diagnostics page. Lists every registered module
//        with a "Run diagnostics" button that exercises all three sync
//        types in force-mode and renders per-step pass/fail.
import { useCallback, useEffect, useState } from "react";
import { CheckCircle2, Loader2, Stethoscope, XCircle } from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard } from "./ui";
import {
  listModules,
  runDiagnostics,
  type ModuleDiagnosticsResult,
  type ModuleSyncSettings,
} from "@/lib/moduleSyncApi";

export default function CmsSyncDiagnostics() {
  const [modules, setModules] = useState<ModuleSyncSettings[]>([]);
  const [loading, setLoading] = useState(true);
  const [results, setResults] = useState<Record<string, ModuleDiagnosticsResult>>({});
  const [running, setRunning] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setModules(await listModules());
    } catch (e) {
      toast.error(`Load failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const runOne = async (moduleName: string) => {
    setRunning(moduleName);
    try {
      const r = await runDiagnostics(moduleName);
      setResults((prev) => ({ ...prev, [moduleName]: r }));
      if (r.ok) toast.success(`${moduleName}: diagnostics passed.`);
      else toast.error(`${moduleName}: some checks failed.`);
    } catch (e) {
      toast.error(`Diagnostics failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setRunning(null);
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        title="Module Sync Diagnostics"
        description="Run live connectivity + fetch checks for every reseller module."
        icon={<Stethoscope className="h-6 w-6" />}
      />

      <SectionCard
        title="Per-module Health Checks"
        description="Each check exercises clients/accounts/domains fetches in force-mode (toggles are ignored)."
      >
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500">
            <Loader2 className="h-4 w-4 animate-spin" /> Loading modules…
          </div>
        ) : (
          <div className="grid gap-4 md:grid-cols-2">
            {modules.map((m) => {
              const r = results[m.module_name];
              const busy = running === m.module_name;
              return (
                <div
                  key={m.module_name}
                  className="rounded-lg border border-slate-200 bg-white p-4 shadow-sm"
                >
                  <div className="flex items-start justify-between">
                    <div>
                      <h4 className="text-sm font-semibold text-slate-800">{m.module_label}</h4>
                      <p className="text-xs text-slate-500">Module key: {m.module_name}</p>
                    </div>
                    <button
                      type="button"
                      onClick={() => void runOne(m.module_name)}
                      disabled={busy}
                      className="inline-flex items-center gap-2 rounded-md bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-700 disabled:opacity-50"
                    >
                      {busy ? <Loader2 className="h-3 w-3 animate-spin" /> : <Stethoscope className="h-3 w-3" />}
                      Run
                    </button>
                  </div>

                  {r ? (
                    <div className="mt-3">
                      <div
                        className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs ${r.ok ? "bg-emerald-100 text-emerald-700 border-emerald-200" : "bg-red-100 text-red-700 border-red-200"}`}
                      >
                        {r.ok ? <CheckCircle2 className="h-3 w-3" /> : <XCircle className="h-3 w-3" />}
                        {r.message ?? (r.ok ? "OK" : "Failed")}
                      </div>
                      <ul className="mt-2 divide-y divide-slate-100 text-sm">
                        {r.steps.map((s) => (
                          <li key={s.step} className="flex items-center justify-between py-1.5">
                            <span className="font-mono text-xs text-slate-600">{s.step}</span>
                            <span className={s.ok ? "text-emerald-700" : "text-red-700"}>{s.detail}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ) : (
                    <p className="mt-3 text-xs text-slate-500">No diagnostics run yet for this module.</p>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </SectionCard>
    </CmsLayout>
  );
}