"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 || cleanedAt) {
      return;
    }

    if (
      !window.confirm(
        `${domain}의 Mailcow 도메인과 대표·멤버 메일함을 삭제할까요?\n\n우리 DB의 가입·결제 이력은 보관되고, 같은 대표 계정과 보조 이메일로 재가입하면 다시 복구할 수 있습니다.`,
      )
    ) {
      return;
    }

    setBusy(true);

    try {
      const response = await fetch(`/api/kavenix/domains/${domainId}/cleanup`, {
        method: "POST",
      });
      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 || Boolean(cleanedAt)}
      className={`inline-flex h-9 items-center justify-center rounded-[10px] px-3 text-[12px] font-semibold transition-colors ${
        cleanedAt
          ? "cursor-not-allowed bg-[#f4f6fa] text-[#9aa8bf]"
          : "cursor-pointer bg-[#fff1f1] text-[#d3484e] hover:bg-[#ffe4e5]"
      }`}
    >
      {busy ? "정리 중..." : cleanedAt ? "정리됨" : "도메인 정리"}
    </button>
  );
}
