"use client";

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

import { BottomToast, type BottomToastNotice } from "@/components/bottom-toast";

type KavenixDomainOperationalBenefitToggleProps = {
  cleanedAt: string | null;
  domain: string;
  domainId: number;
  enabled: boolean;
};

type OperationalBenefitResponse = {
  message?: string;
  ok?: boolean;
  result?: {
    operationalBenefitEnabled?: boolean;
  };
};

export function KavenixDomainOperationalBenefitToggle({
  cleanedAt,
  domain,
  domainId,
  enabled: initialEnabled,
}: KavenixDomainOperationalBenefitToggleProps) {
  const router = useRouter();
  const [busy, setBusy] = useState(false);
  const [confirmed, setConfirmed] = useState(false);
  const [enabled, setEnabled] = useState(initialEnabled);
  const [open, setOpen] = useState(false);
  const [toast, setToast] = useState<BottomToastNotice | null>(null);
  const nextEnabled = !enabled;

  useEffect(() => {
    if (!open) {
      return;
    }

    function handleKeyDown(event: KeyboardEvent) {
      if (event.key === "Escape" && !busy) {
        setOpen(false);
        setConfirmed(false);
      }
    }

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [busy, open]);

  useEffect(() => {
    if (!toast) {
      return;
    }

    const timeoutId = window.setTimeout(() => setToast(null), 3600);
    return () => window.clearTimeout(timeoutId);
  }, [toast]);

  function closeDialog() {
    if (busy) {
      return;
    }

    setOpen(false);
    setConfirmed(false);
  }

  async function submitChange() {
    if (busy || !confirmed) {
      return;
    }

    setBusy(true);

    try {
      const response = await fetch(
        `/api/kavenix/domains/${domainId}/operational-benefit`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ enabled: nextEnabled }),
        },
      );
      const payload = (await response.json()) as OperationalBenefitResponse;

      if (!response.ok || payload.ok !== true) {
        throw new Error(payload.message || "운영 계정 혜택을 변경하지 못했습니다.");
      }

      const resolvedEnabled =
        typeof payload.result?.operationalBenefitEnabled === "boolean"
          ? payload.result.operationalBenefitEnabled
          : nextEnabled;
      setEnabled(resolvedEnabled);
      setOpen(false);
      setConfirmed(false);
      setToast({
        message: payload.message || "운영 계정 혜택을 변경했습니다.",
        tone: "success",
      });
      router.refresh();
    } catch (error) {
      setToast({
        message:
          error instanceof Error
            ? error.message
            : "운영 계정 혜택을 변경하지 못했습니다.",
        tone: "error",
      });
    } finally {
      setBusy(false);
    }
  }

  return (
    <>
      <div className="flex items-center justify-end gap-2">
        <span className={`text-[11px] font-semibold ${enabled ? "text-[#2f6df6]" : "text-[#7d8da7]"}`}>
          운영 혜택
        </span>
        <button
          type="button"
          role="switch"
          aria-checked={enabled}
          aria-label={`${domain} 운영 계정 혜택 ${enabled ? "해제" : "부여"}`}
          disabled={busy || Boolean(cleanedAt)}
          onClick={() => {
            setConfirmed(false);
            setOpen(true);
          }}
          className={`relative h-6 w-11 shrink-0 rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#8db8ff] focus-visible:ring-offset-2 ${
            cleanedAt
              ? "cursor-not-allowed bg-[#dce3ee]"
              : enabled
                ? "cursor-pointer bg-[#2f6df6]"
                : "cursor-pointer bg-[#d5ddea] hover:bg-[#c7d2e3]"
          }`}
        >
          <span
            className={`absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white shadow-[0_1px_4px_rgba(24,52,96,0.28)] transition-transform duration-200 ${
              enabled ? "translate-x-5" : "translate-x-0"
            }`}
          />
        </button>
      </div>

      {open ? (
        <div
          className="fixed inset-0 z-[10050] flex items-center justify-center bg-[#0f1f38]/34 px-4 py-8 backdrop-blur-[3px]"
          role="presentation"
          onMouseDown={(event) => {
            if (event.currentTarget === event.target) {
              closeDialog();
            }
          }}
        >
          <section
            role="dialog"
            aria-modal="true"
            aria-labelledby={`operational-benefit-title-${domainId}`}
            className="w-full max-w-[470px] overflow-hidden rounded-[24px] border border-white/90 bg-white text-left shadow-[0_28px_80px_rgba(18,32,65,0.22)]"
          >
            <div className="px-5 pb-4 pt-5 sm:px-6 sm:pt-6">
              <p className="text-[12px] font-semibold text-[#2f6df6]">운영 계정 혜택</p>
              <h2
                id={`operational-benefit-title-${domainId}`}
                className="mt-1.5 text-[20px] font-semibold tracking-[-0.045em] text-[#16233c]"
              >
                {nextEnabled ? "혜택을 부여할까요?" : "혜택을 해제할까요?"}
              </h2>
              <p className="mt-3 break-all text-[14px] font-semibold text-[#30425f]">{domain}</p>
              <p className="mt-2 text-[13px] leading-6 text-[#667894]">
                {nextEnabled
                  ? "결제 없이 성장 플랜 기능과 메일함 용량을 사용할 수 있게 됩니다. 정기결제 대상에서도 제외됩니다."
                  : "활성 결제가 없다면 무료 플랜 권한과 용량으로 돌아갑니다. 저장된 메일은 삭제되지 않지만 용량을 초과하면 새 메일 수신이 제한될 수 있습니다."}
              </p>
            </div>

            <label className="mx-5 flex cursor-pointer items-start gap-3 rounded-[14px] border border-[#e1e8f4] bg-[#f8faff] px-4 py-3.5 sm:mx-6">
              <input
                type="checkbox"
                checked={confirmed}
                onChange={(event) => setConfirmed(event.target.checked)}
                className="mt-0.5 h-4 w-4 rounded border-[#cbd6e8] text-[#2f6df6] focus:ring-[#9ebcff]"
              />
              <span className="text-[13px] leading-5 text-[#425573]">
                적용 범위와 과금 변경 내용을 확인했습니다.
              </span>
            </label>

            <div className="mt-5 flex items-center justify-end gap-2 border-t border-[#edf1f6] px-5 py-4 sm:px-6">
              <button
                type="button"
                onClick={closeDialog}
                disabled={busy}
                className="h-10 cursor-pointer rounded-[10px] px-4 text-[13px] font-semibold text-[#667894] transition-colors hover:bg-[#f3f6fb] disabled:cursor-not-allowed"
              >
                취소
              </button>
              <button
                type="button"
                onClick={submitChange}
                disabled={busy || !confirmed}
                className={`h-10 rounded-[10px] px-4 text-[13px] font-semibold text-white transition-colors ${
                  busy || !confirmed
                    ? "cursor-not-allowed bg-[#aabce0]"
                    : nextEnabled
                      ? "cursor-pointer bg-[#2f6df6] hover:bg-[#245de3]"
                      : "cursor-pointer bg-[#d94f55] hover:bg-[#c94248]"
                }`}
              >
                {busy ? "변경 중..." : nextEnabled ? "혜택 부여" : "혜택 해제"}
              </button>
            </div>
          </section>
        </div>
      ) : null}

      {toast ? <BottomToast notice={toast} onClose={() => setToast(null)} /> : null}
    </>
  );
}
