"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Modal from "./Modal";
import { disconnectSiteAction } from "@/lib/actions/site-actions";

export default function DisconnectSiteButton({
  siteId,
  siteName,
}: {
  siteId: string;
  siteName: string;
}) {
  const router = useRouter();
  const [confirmName, setConfirmName] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(close: () => void) {
    setError(null);
    setLoading(true);
    const fd = new FormData();
    fd.set("siteId", siteId);
    fd.set("confirmName", confirmName);
    try {
      await disconnectSiteAction(fd);
      close();
      router.push("/sites");
      router.refresh();
    } catch (e: any) {
      setError(e?.message ?? "Something went wrong.");
      setLoading(false);
    }
  }

  return (
    <Modal
      title="Disconnect this site"
      trigger={
        <button
          data-testid="disconnect-trigger"
          className="bg-transparent border border-error text-error font-bold text-[12.5px] px-3.5 py-2 rounded-lg"
        >
          Disconnect site
        </button>
      }
    >
      {(close) => (
        <div className="flex flex-col gap-3.5">
          <div className="text-sm text-text-secondary">
            This removes <span className="font-mono text-text-primary">{siteName}</span> from
            Webstation and revokes any site-scoped access grants for it. This does not delete or
            change anything on the actual WordPress install. Type the site name to confirm.
          </div>
          <input
            value={confirmName}
            onChange={(e) => setConfirmName(e.target.value)}
            placeholder={siteName}
            className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm font-mono outline-none"
          />
          {error && <div className="text-[12px] text-error">{error}</div>}
          <div className="flex gap-2.5 justify-end">
            <button
              onClick={close}
              className="bg-transparent border border-border-input text-text-secondary font-semibold text-sm px-3.5 py-2 rounded-lg"
            >
              Cancel
            </button>
            <button
              data-testid="disconnect-confirm"
              onClick={() => handleSubmit(close)}
              disabled={loading || confirmName.trim() !== siteName}
              className="bg-error text-white font-bold text-sm px-4 py-2 rounded-lg disabled:opacity-40"
            >
              {loading ? "Disconnecting…" : "Disconnect site"}
            </button>
          </div>
        </div>
      )}
    </Modal>
  );
}
