// @File: src/pages/admin/cms/uptimerobot/CmsUptimeRobotApiSettings.tsx
// @Desc: API key management + connection test + sync-now for the master
//        UptimeRobot Team account.
import { useCallback, useEffect, useState } from "react";
import {
  KeyRound,
  Loader2,
  RefreshCw,
  Save,
  CheckCircle2,
  XCircle,
} from "lucide-react";
import { toast } from "sonner";
import CmsLayout from "../CmsLayout";
import { PageHeader, SectionCard, Field, TextInput } from "../ui";
import {
  adminGetApiSettings,
  adminSaveApiKey,
  adminSyncNow,
  adminTestApiKey,
  type UptimeApiSettings,
  type UptimeApiTestResult,
} from "@/lib/uptimerobotApi";

export default function CmsUptimeRobotApiSettings() {
  const [settings, setSettings] = useState<UptimeApiSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [keyInput, setKeyInput] = useState("");
  const [lastTest, setLastTest] = useState<UptimeApiTestResult | null>(null);

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

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

  const save = async () => {
    if (!keyInput.trim()) {
      toast.error("API key is required.");
      return;
    }
    setSaving(true);
    try {
      const s = await adminSaveApiKey(keyInput.trim());
      setSettings(s);
      setKeyInput("");
      toast.success("API key saved (encrypted at rest).");
    } catch (e) {
      toast.error(`Save failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setSaving(false);
    }
  };

  const test = async () => {
    setTesting(true);
    setLastTest(null);
    try {
      const r = await adminTestApiKey();
      setLastTest(r);
      if (r.ok) {
        toast.success(`Connection OK. Plan: ${r.plan_name ?? "unknown"}`);
      } else {
        toast.error(`Connection failed: ${r.error_message ?? r.error_class}`);
      }
    } catch (e) {
      toast.error(`Test failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setTesting(false);
    }
  };

  const sync = async () => {
    setSyncing(true);
    try {
      const r = await adminSyncNow();
      if (r.ok) {
        toast.success(`Sync complete. ${r.monitors_synced} monitors updated.`);
      } else {
        toast.warning(r.error ?? "Sync completed with warnings.");
      }
      await load();
    } catch (e) {
      toast.error(`Sync failed: ${e instanceof Error ? e.message : e}`);
    } finally {
      setSyncing(false);
    }
  };

  return (
    <CmsLayout>
      <PageHeader
        title="API Settings"
        description="Manage the master UptimeRobot API key used by all client operations. Values are encrypted at rest using the portal's secret manager."
        icon={<KeyRound className="w-6 h-6" />}
      />

      <SectionCard title="Master API key">
        {loading ? (
          <div className="flex items-center gap-2 text-slate-500 text-sm">
            <Loader2 className="w-4 h-4 animate-spin" /> Loading…
          </div>
        ) : settings ? (
          <>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
              <StatusTile
                label="Status"
                value={
                  settings.api_key_present ? (
                    <span className="text-emerald-700 inline-flex items-center gap-1">
                      <CheckCircle2 className="w-4 h-4" /> Configured
                    </span>
                  ) : (
                    <span className="text-red-700 inline-flex items-center gap-1">
                      <XCircle className="w-4 h-4" /> Not configured
                    </span>
                  )
                }
              />
              <StatusTile
                label="Source"
                value={settings.api_key_source.toUpperCase()}
              />
              <StatusTile
                label="Masked value"
                value={settings.api_key_masked ?? "—"}
              />
            </div>
            <Field
              label="Paste a new API key"
              hint="Submit to rotate. Existing value will be overwritten."
            >
              <TextInput
                type="password"
                value={keyInput}
                onChange={(e) => setKeyInput(e.target.value)}
                placeholder="ur-m1234567-xxxxxxxxxxxxxxxxxxxxxxxx"
              />
            </Field>
            <div className="flex flex-wrap items-center gap-2 pt-3">
              <button
                onClick={save}
                disabled={saving || !keyInput}
                className="px-4 py-2 rounded-lg bg-[#0b6e3e] text-white text-sm font-semibold hover:bg-[#095a32] inline-flex items-center gap-2 disabled:opacity-60"
              >
                {saving ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                Save key
              </button>
              <button
                onClick={test}
                disabled={testing || !settings.api_key_present}
                className="px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold inline-flex items-center gap-2 disabled:opacity-60"
              >
                {testing ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <CheckCircle2 className="w-4 h-4" />
                )}
                Test connection
              </button>
              <button
                onClick={sync}
                disabled={syncing || !settings.api_key_present}
                className="px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold inline-flex items-center gap-2 disabled:opacity-60"
              >
                {syncing ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <RefreshCw className="w-4 h-4" />
                )}
                Sync now
              </button>
            </div>
          </>
        ) : null}
      </SectionCard>

      {settings && (
        <div className="mt-6">
          <SectionCard title="Recent health">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <StatusTile
                label="Last successful call"
                value={
                  settings.last_sync_at
                    ? new Date(settings.last_sync_at).toLocaleString()
                    : "—"
                }
              />
              <StatusTile
                label="Last error"
                value={
                  settings.last_error_at ? (
                    <>
                      <div className="text-red-700 font-bold text-sm">
                        {settings.last_error_class ?? "error"}
                      </div>
                      <div className="text-xs text-slate-500">
                        {new Date(settings.last_error_at).toLocaleString()}
                      </div>
                      {settings.last_error_message && (
                        <div className="text-xs text-slate-600 mt-1">
                          {settings.last_error_message}
                        </div>
                      )}
                    </>
                  ) : (
                    <span className="text-emerald-700 font-semibold">
                      None recorded
                    </span>
                  )
                }
              />
            </div>
          </SectionCard>
        </div>
      )}

      {lastTest && (
        <div className="mt-6">
          <SectionCard title="Last connection test">
            {lastTest.ok ? (
              <div className="text-sm text-emerald-700 inline-flex items-center gap-2">
                <CheckCircle2 className="w-5 h-5" />
                Success · Plan: {lastTest.plan_name ?? "unknown"}
              </div>
            ) : (
              <div className="text-sm text-red-700">
                <div className="inline-flex items-center gap-2 font-semibold">
                  <XCircle className="w-5 h-5" /> Failed
                </div>
                <div className="mt-1">
                  Class: {lastTest.error_class ?? "?"} · HTTP:{" "}
                  {lastTest.http_status ?? "—"}
                </div>
                <div className="text-xs text-slate-600 mt-1">
                  {lastTest.error_message}
                </div>
              </div>
            )}
          </SectionCard>
        </div>
      )}
    </CmsLayout>
  );
}

function StatusTile({
  label,
  value,
}: {
  label: string;
  value: React.ReactNode;
}) {
  return (
    <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
      <div className="text-[11px] uppercase tracking-wide text-slate-500 font-semibold">
        {label}
      </div>
      <div className="mt-1 text-slate-900 font-semibold text-sm">{value}</div>
    </div>
  );
}