"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { loadTossPayments } from "@tosspayments/tosspayments-sdk";

import type { TossPaymentsBillingAuthSession } from "@/lib/toss-pay";

export function TossPaymentsBillingAuth({
  session,
}: {
  session: TossPaymentsBillingAuthSession;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const requestInFlightRef = useRef(false);
  const requestedOnMountRef = useRef(false);

  const openCardRegistration = useCallback(async () => {
    if (requestInFlightRef.current) {
      return;
    }

    requestInFlightRef.current = true;
    setBusy(true);
    setError(null);

    try {
      const tossPayments = await loadTossPayments(session.clientKey);
      const payment = tossPayments.payment({ customerKey: session.customerKey });

      await payment.requestBillingAuth({
        method: "CARD",
        successUrl: session.successUrl,
        failUrl: session.failUrl,
        customerEmail: session.customerEmail,
        customerName: session.customerName,
        selectableCardTypes: ["PERSONAL", "CORPORATE"],
        windowTarget: "self",
      });
    } catch (requestError) {
      const message =
        requestError instanceof Error
          ? requestError.message
          : "카드 등록창을 열지 못했습니다. 잠시 후 다시 시도해주세요.";
      setError(message);
      requestInFlightRef.current = false;
      setBusy(false);
    }
  }, [session]);

  useEffect(() => {
    if (requestedOnMountRef.current) {
      return;
    }

    requestedOnMountRef.current = true;
    void openCardRegistration();
  }, [openCardRegistration]);

  return (
    <main className="flex min-h-screen items-center justify-center bg-[#f5f8ff] px-4">
      {error ? (
        <section className="w-full max-w-[420px] rounded-[22px] border border-[#dfe8f8] bg-white px-6 py-7 text-center shadow-[0_24px_64px_rgba(24,44,86,0.1)]">
          <h1 className="text-[20px] font-bold tracking-[-0.04em] text-[#111a33]">
            카드 등록창을 열지 못했습니다
          </h1>
          <p role="alert" className="mt-3 text-[13px] leading-6 text-[#66758f]">
            {error}
          </p>
          <button
            type="button"
            onClick={() => void openCardRegistration()}
            disabled={busy}
            className="mt-5 inline-flex h-11 w-full cursor-pointer items-center justify-center rounded-[13px] bg-[#2f6df6] px-5 text-[14px] font-bold text-white transition-colors hover:bg-[#245de3] disabled:cursor-wait disabled:opacity-65"
          >
            다시 시도
          </button>
        </section>
      ) : (
        <div role="status" className="flex items-center gap-3 text-[14px] font-semibold text-[#526988]">
          <span className="h-5 w-5 animate-spin rounded-full border-2 border-[#c8d7ef] border-t-[#2f6df6]" />
          토스페이먼츠 카드 등록창을 여는 중입니다
        </div>
      )}
    </main>
  );
}
