"use client";

/**
 * Test-connection button for /admin/ai. Lives next to the "Lưu thay đổi"
 * button. Reads the current values directly from the settings form so
 * admin can test BEFORE saving — no risk of saving a bad key.
 */
import { useState } from "react";
import { Plug, Check, AlertCircle, Loader2 } from "lucide-react";

type TestResult = {
  ok: true;
  sample: string;
  provider: string;
  model: string;
};

export function AiTestButton() {
  const [pending, setPending] = useState(false);
  const [result, setResult] = useState<TestResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function run(provider: "openai" | "anthropic") {
    setPending(true);
    setResult(null);
    setError(null);

    // Pull current values from the form. Client-side DOM access — works
    // because this component is rendered inside the same <form> wrapper.
    const form = document.querySelector("form") as HTMLFormElement | null;
    const fd = form ? new FormData(form) : null;
    const keyField = provider === "openai" ? "ai.openai_api_key" : "ai.anthropic_api_key";
    const modelField = provider === "openai" ? "ai.openai_model" : "ai.anthropic_model";

    const apiKey = fd ? String(fd.get(keyField) ?? "") : "";
    const model = fd ? String(fd.get(modelField) ?? "") : "";
    const baseURL = fd && provider === "openai" ? String(fd.get("ai.openai_base_url") ?? "") : "";

    try {
      const res = await fetch("/api/admin/ai/test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ provider, apiKey, model, baseURL }),
      });
      const data = (await res.json()) as TestResult | { error: string };
      if (!res.ok || "error" in data) {
        setError("error" in data ? data.error : `HTTP ${res.status}`);
      } else {
        setResult(data);
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : "Network error");
    } finally {
      setPending(false);
    }
  }

  return (
    <div className="border-stroke-subtle bg-bg-elevated/40 mt-2 rounded-xl border p-4">
      <div className="flex flex-wrap items-center gap-2">
        <span className="text-ink-secondary text-xs">
          Test kết nối (dùng giá trị trong form, không cần lưu trước):
        </span>
        <button
          type="button"
          onClick={() => void run("openai")}
          disabled={pending}
          className="border-stroke-default text-ink-primary hover:border-brand-gold/50 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50"
        >
          {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plug className="h-3 w-3" />}
          OpenAI
        </button>
        <button
          type="button"
          onClick={() => void run("anthropic")}
          disabled={pending}
          className="border-stroke-default text-ink-primary hover:border-brand-gold/50 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs disabled:opacity-50"
        >
          {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Plug className="h-3 w-3" />}
          Anthropic
        </button>
      </div>

      {result ? (
        <div className="mt-3 rounded-md border border-emerald-500/30 bg-emerald-500/10 p-3 text-xs">
          <div className="mb-1 inline-flex items-center gap-1.5 font-semibold text-emerald-400">
            <Check className="h-3.5 w-3.5" />
            {result.provider} · {result.model} kết nối thành công
          </div>
          <div className="text-ink-secondary mt-1">
            Phản hồi mẫu:{" "}
            <span className="text-ink-primary font-mono">
              {result.sample.length > 120 ? result.sample.slice(0, 120) + "..." : result.sample}
            </span>
          </div>
        </div>
      ) : null}

      {error ? (
        <div className="border-brand-red/40 bg-brand-red/10 text-brand-red-light mt-3 rounded-md border p-3 text-xs">
          <div className="mb-1 inline-flex items-center gap-1.5 font-semibold">
            <AlertCircle className="h-3.5 w-3.5" />
            Test thất bại
          </div>
          <div className="font-mono">{error}</div>
        </div>
      ) : null}
    </div>
  );
}
