"use client";

import { useState } from "react";
import { PlugZap } from "lucide-react";
import toast from "react-hot-toast";

export default function CJConnectionTest() {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);

  const test = async () => {
    setLoading(true);
    setResult(null);
    try {
      const res = await fetch("/api/admin/cj/test", { method: "POST" });
      const data = await res.json();
      if (data.ok) {
        setResult({ ok: true, message: `Token obtained via ${data.mode} — ${data.tokenPreview}` });
        toast.success("CJ connection works.");
      } else {
        setResult({ ok: false, message: data.error ?? "Connection failed." });
        toast.error("CJ connection failed.");
      }
    } catch {
      setResult({ ok: false, message: "Could not reach the test endpoint." });
      toast.error("Could not reach the test endpoint.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={test} disabled={loading} className="btn-outline text-sm disabled:opacity-60">
        <PlugZap className={`h-4 w-4 ${loading ? "animate-pulse" : ""}`} />
        {loading ? "Testing..." : "Test CJ connection"}
      </button>
      {result && (
        <p className={`text-xs mt-2 ${result.ok ? "text-green-600" : "text-red-600"}`}>{result.message}</p>
      )}
    </div>
  );
}
