import { useState } from "react";
import { Plug, Loader2, Check, X } from "lucide-react";
import { stalkerApi, isValidMac } from "@/lib/stalker";
import { toast } from "sonner";

type Status = "idle" | "loading" | "ok" | "fail";

interface Props {
  portalUrl: string;
  mac: string;
  testId?: string;
  /** When true, render as a small icon-only pill (used inside admin rows). */
  compact?: boolean;
}

/**
 * "Test Connection" button — runs a fresh `/api/stalker/handshake` against the
 * supplied portal + MAC and surfaces the result inline (and via toast). Useful
 * as a pre-flight check before saving a profile so users catch typos early.
 */
const StalkerTestButton = ({ portalUrl, mac, testId, compact = false }: Props) => {
  const [status, setStatus] = useState<Status>("idle");
  const [detail, setDetail] = useState<string>("");

  const disabled =
    status === "loading" ||
    !portalUrl.trim() ||
    !isValidMac(mac.trim());

  const run = async () => {
    if (disabled) return;
    setStatus("loading");
    setDetail("");
    const tId = toast.loading("Contacting Stalker portal…");
    try {
      const res = await stalkerApi.handshake(portalUrl.trim(), mac.trim().toUpperCase());
      setStatus("ok");
      const expires = res.profile.expire_billing_date;
      const name = res.profile.name || res.profile.mac || "device";
      setDetail(expires ? `Active until ${expires}` : "Connection OK");
      toast.success(
        `Stalker portal accepted ${name}` +
          (expires ? ` · expires ${expires}` : ""),
        { id: tId },
      );
    } catch (e: any) {
      setStatus("fail");
      const msg = e?.message || "Connection failed";
      setDetail(msg);
      toast.error(`Test failed: ${msg}`, { id: tId });
    }
  };

  const Icon =
    status === "loading"
      ? Loader2
      : status === "ok"
        ? Check
        : status === "fail"
          ? X
          : Plug;

  const colour =
    status === "ok"
      ? "text-emerald-400 border-emerald-500/40"
      : status === "fail"
        ? "text-destructive border-destructive/40"
        : "text-primary hover:border-primary/40";

  if (compact) {
    return (
      <button
        type="button"
        onClick={run}
        disabled={disabled}
        data-testid={testId}
        title="Test connection"
        className={`flex items-center justify-center w-8 h-8 rounded-lg glass border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${colour}`}
      >
        <Icon className={`w-3.5 h-3.5 ${status === "loading" ? "animate-spin" : ""}`} />
      </button>
    );
  }

  return (
    <div className="space-y-1.5">
      <button
        type="button"
        onClick={run}
        disabled={disabled}
        data-testid={testId}
        className={`w-full flex items-center justify-center gap-2 py-2 rounded-lg glass border text-xs font-medium tracking-[0.15em] uppercase transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${colour}`}
      >
        <Icon className={`w-3.5 h-3.5 ${status === "loading" ? "animate-spin" : ""}`} />
        {status === "loading"
          ? "Testing…"
          : status === "ok"
            ? "Connected"
            : status === "fail"
              ? "Failed — try again"
              : "Test Connection"}
      </button>
      {detail && (
        <p
          data-testid={testId ? `${testId}-detail` : undefined}
          className={`text-[10px] px-1 leading-relaxed ${
            status === "ok" ? "text-emerald-400/80" : "text-muted-foreground"
          }`}
        >
          {detail}
        </p>
      )}
    </div>
  );
};

export default StalkerTestButton;
