"use client";

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

type RepairResponse = {
  message?: string;
  ok?: boolean;
  result?: {
    failed?: Array<{ domain: string; error: string }>;
  };
};

export function KavenixDomainRepairButton({
  domain,
  domainId,
}: {
  domain: string;
  domainId: number;
}) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

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

    if (
      !window.confirm(
        `${domain}의 메일 연결을 복구할까요?\n\n도메인 형식과 Mailcow 상태를 확인한 뒤 누락된 대표 메일함을 생성하고 DNS도 다시 검증합니다. DNS가 아직 미완료여도 메일함은 먼저 복구하며, 고객 DNS 안내값과 DKIM 키는 변경하지 않습니다.`,
      )
    ) {
      return;
    }

    setBusy(true);

    try {
      const response = await fetch(`/api/kavenix/domains/${domainId}/repair`, {
        method: "POST",
      });
      const payload = (await response.json()) as RepairResponse;

      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={repair}
      disabled={busy}
      className="inline-flex h-9 cursor-pointer items-center justify-center rounded-[10px] bg-[#e9485d] px-3 text-[12px] font-semibold text-white transition-colors hover:bg-[#d63b50] disabled:cursor-not-allowed disabled:bg-[#e7a3ad]"
    >
      {busy ? "복구 중..." : "메일 연결 복구"}
    </button>
  );
}

export function KavenixDomainRepairAllButton({ issueCount }: { issueCount: number }) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);

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

    if (
      !window.confirm(
        `전체 도메인의 메일 연결 상태를 점검할까요?\n\n형식이 정상인 도메인은 DNS 완료 여부와 관계없이 누락된 대표 메일함을 자동 복구하고 DNS도 다시 검증합니다. 형식이 잘못된 도메인은 제외하며, 고객 DNS 안내값과 DKIM 키는 변경하지 않습니다.`,
      )
    ) {
      return;
    }

    setBusy(true);

    try {
      const response = await fetch("/api/kavenix/domains/repair-all", {
        method: "POST",
      });
      const payload = (await response.json()) as RepairResponse;

      if (!response.ok || payload.ok !== true) {
        throw new Error(payload.message || "일괄 점검에 실패했습니다.");
      }

      const failedDomains = payload.result?.failed?.map((item) => item.domain) ?? [];
      const detail =
        failedDomains.length > 0
          ? `\n\n추가 확인 필요: ${failedDomains.join(", ")}`
          : "";
      window.alert(`${payload.message || "일괄 점검을 완료했습니다."}${detail}`);
      router.refresh();
    } catch (error) {
      window.alert(error instanceof Error ? error.message : "일괄 점검에 실패했습니다.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <button
      type="button"
      onClick={repairAll}
      disabled={busy}
      className="inline-flex h-10 cursor-pointer items-center justify-center rounded-[11px] bg-[#2f6df6] px-4 text-[13px] font-semibold text-white transition-colors hover:bg-[#245de3] disabled:cursor-not-allowed disabled:bg-[#9dbcfb]"
    >
      {busy
        ? "전체 점검 중..."
        : issueCount > 0
          ? `메일 연결 오류 ${issueCount}건 일괄 복구`
          : "메일 연결 오류 전체 점검"}
    </button>
  );
}
