"use client";

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

type KavenixCancellationReviewActionsProps = {
  className?: string;
  remainingRefundableAmount: number;
  requestId: number;
};

type ReviewAction = "approve_full" | "approve_partial" | "reject";

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

function buttonClass(tone: "primary" | "secondary" | "danger") {
  if (tone === "primary") {
    return "om-btn-primary h-10 rounded-[12px] px-4 text-[12px] font-semibold";
  }

  if (tone === "danger") {
    return "h-10 rounded-[12px] border border-[#f0d6de] bg-[#fff4f7] px-4 text-[12px] font-semibold text-[#b24463] transition-colors hover:bg-[#ffeaf0]";
  }

  return "om-btn-secondary h-10 rounded-[12px] px-4 text-[12px] font-semibold text-[#344767]";
}

export function KavenixCancellationReviewActions({
  className,
  remainingRefundableAmount,
  requestId,
}: KavenixCancellationReviewActionsProps) {
  const router = useRouter();
  const [busyAction, setBusyAction] = useState<ReviewAction | null>(null);

  async function submitReview(input: {
    action: ReviewAction;
    note?: string | null;
    refundAmount?: number | null;
  }) {
    setBusyAction(input.action);

    try {
      const response = await fetch(`/api/kavenix/cancellations/${requestId}/review`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(input),
      });

      const payload = (await response.json()) as ReviewApiResponse;

      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 {
      setBusyAction(null);
    }
  }

  async function handleApproveFull() {
    const note = window.prompt("승인 메모를 남길까요?", "전액 청약철회 승인");

    if (note === null) {
      return;
    }

    if (!window.confirm("이 청약철회 요청을 승인할까요?")) {
      return;
    }

    await submitReview({
      action: "approve_full",
      note: note.trim(),
    });
  }

  async function handleApprovePartial() {
    const amountText = window.prompt(
      `부분 환불 금액을 입력하세요. 최대 ${remainingRefundableAmount.toLocaleString("ko-KR")}원까지 가능합니다.`,
      String(remainingRefundableAmount),
    );

    if (amountText === null) {
      return;
    }

    const refundAmount = Math.floor(Number(amountText.replace(/[^\d.-]/g, "")));

    if (!Number.isFinite(refundAmount) || refundAmount <= 0) {
      window.alert("부분 환불 금액을 숫자로 입력해 주세요.");
      return;
    }

    const note = window.prompt("부분 환불 사유나 메모를 남길까요?", "부분 환불 청약철회 승인");

    if (note === null) {
      return;
    }

    if (
      !window.confirm(
        `${refundAmount.toLocaleString("ko-KR")}원 부분 환불로 청약철회 요청을 승인할까요?`,
      )
    ) {
      return;
    }

    await submitReview({
      action: "approve_partial",
      note: note.trim(),
      refundAmount,
    });
  }

  async function handleReject() {
    const note = window.prompt("반려 사유를 입력하세요.", "청약철회 반려");

    if (note === null) {
      return;
    }

    if (!window.confirm("이 청약철회 요청을 반려할까요?")) {
      return;
    }

    await submitReview({
      action: "reject",
      note: note.trim(),
    });
  }

  return (
    <div className={className}>
      <button
        type="button"
        onClick={handleApproveFull}
        disabled={busyAction !== null}
        className={buttonClass("primary")}
      >
        {busyAction === "approve_full" ? "승인 중..." : "청약철회 승인"}
      </button>
      <button
        type="button"
        onClick={handleApprovePartial}
        disabled={busyAction !== null}
        className={buttonClass("secondary")}
      >
        {busyAction === "approve_partial" ? "부분환불 처리 중..." : "부분환불 승인"}
      </button>
      <button
        type="button"
        onClick={handleReject}
        disabled={busyAction !== null}
        className={buttonClass("danger")}
      >
        {busyAction === "reject" ? "반려 중..." : "반려"}
      </button>
    </div>
  );
}
