"use client";
/**
 * 订阅 checkout 触发按钮
 *
 * 包装 `SubscriptionCtaButton` —— 通过 payment 状态机创建后端订单并拉起支付。
 */
import { usePaymentLaunchFlow } from "@/app/_hooks/use-payment-launch-flow";
import { PaymentLaunchDialogs } from "@/app/_components/payment/payment-launch-dialogs";
import { DEFAULT_CHARACTER_SLUG } from "@/data/constants/character";
import type { SubscriptionReturnTo } from "@/lib/navigation/subscription_exit";
import {
  usePaymentDispatch,
  usePaymentState,
} from "@/stores/payment/payment-context";
import { Logger } from "@/utils/logger";

import { SubscriptionCtaButton } from "./subscription-cta-button";

const log = new Logger("SubscriptionCheckoutButton");

export interface SubscriptionCheckoutButtonProps {
  /** 是否可用（未选套餐 / 未勾选协议 → false） */
  disabled?: boolean;
  subscriptionType: "vip" | "topup";
  returnTo?: SubscriptionReturnTo;
  sourceCharacterSlug?: string;
}

export function SubscriptionCheckoutButton({
  disabled = false,
  subscriptionType,
  returnTo = null,
  sourceCharacterSlug = DEFAULT_CHARACTER_SLUG,
}: SubscriptionCheckoutButtonProps) {
  const payment = usePaymentState();
  const paymentDispatch = usePaymentDispatch();
  const paymentLaunch = usePaymentLaunchFlow({
    log,
    logScope: "subscription-checkout",
    payment,
    paymentDispatch,
    returnTo: returnTo ?? undefined,
    characterSlug: sourceCharacterSlug,
    subscriptionType,
  });

  const isLoading =
    payment.isCreatingOrder ||
    payment.isPollingOrder;
  const readyLabel =
    subscriptionType === "topup" ? "Pay and Top Up" : "Pay and Activiate";
  const agreementLabel =
    subscriptionType === "topup"
      ? "Confirm the agreement and Top Up"
      : "Confirm the agreement and Activate";
  const label = payment.isPollingOrder
      ? "Processing payment..."
      : payment.isCreatingOrder
        ? "Creating order..."
        : payment.agreed
          ? readyLabel
          : agreementLabel;

  const handleClick = () => {
    if (disabled || isLoading) return;
    paymentLaunch.resetLaunchState();
    paymentDispatch({ type: "PaymentCreateOrderSubmitted" });
  };

  return (
    <>
      <SubscriptionCtaButton
        type="button"
        data-analytics-key="subscription.checkout"
        data-analytics-label="Start subscription checkout"
        disabled={disabled}
        isLoading={isLoading}
        onClick={handleClick}
      >
        {label}
      </SubscriptionCtaButton>
      {payment.errorMessage ? (
        <p
          role="alert"
          style={{
            color: "#c0392b",
            fontSize: "0.875rem",
            marginTop: "0.5rem",
            textAlign: "center",
          }}
        >
          {payment.errorMessage}
        </p>
      ) : null}
      <PaymentLaunchDialogs
        currentOrderId={payment.currentOrderId}
        externalCheckoutAnalyticsKey="subscription.external_checkout"
        ezpayDescription="Your order has been created. Continue to GCash to finish the payment."
        launch={paymentLaunch}
      />
    </>
  );
}
