"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

type KavenixDomainCleanupButtonProps = {
  cleanedAt: string | null;
  domain: string;
  domainId: number;
};

type CleanupResponse = {
  message?: string;
  ok?: boolean;
};

export function KavenixDomainCleanupButton({
  cleanedAt,
  domain,
  domainId,
}: KavenixDomainCleanupButtonProps) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

  async function handleCleanup() {
    if (busy) {
      return;
    }

    const confirmationDomain = window.prompt(
      `${domain}의 대표계정, 멤버계정, 모든 도메인, 메일과 설정을 영구 삭제합니다.\n삭제 후 복구할 수 없으며 같은 도메인은 신규 가입에 다시 사용할 수 있습니다.\n\n계속하려면 도메인을 정확히 입력하세요.`,
      "",
    );

    if (confirmationDomain?.trim().toLowerCase() !== domain.trim().toLowerCase()) {
      if (confirmationDomain !== null) {
        window.alert("도메인이 일치하지 않아 삭제하지 않았습니다.");
      }
      return;
    }

    setBusy(true);

    try {
      const response = await fetch(`/api/kavenix/domains/${domainId}/cleanup`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ confirmationDomain }),
      });
      const payload = (await response.json()) as CleanupResponse;

      if (!response.ok || payload.ok !== true) {
        throw new Error(payload.message || "도메인 정리에 실패했습니다.");
      }

      window.alert(payload.message || "도메인이 정리되었습니다.");
      router.refresh();
    } catch (error) {
      window.alert(error instanceof Error ? error.message : "도메인 정리에 실패했습니다.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <button
      type="button"
      onClick={handleCleanup}
      disabled={busy}
      className={`inline-flex h-9 items-center justify-center rounded-[10px] px-3 text-[12px] font-semibold transition-colors ${
        busy
          ? "cursor-not-allowed bg-[#f4f6fa] text-[#9aa8bf]"
          : "cursor-pointer bg-[#fff1f1] text-[#d3484e] hover:bg-[#ffe4e5]"
      }`}
    >
      {busy ? "삭제 중..." : cleanedAt ? "계정·데이터 삭제" : "도메인 정리"}
    </button>
  );
}
