"use client";
/**
 * 订阅 checkout 触发按钮
 *
 * 包装 `SubscriptionCtaButton` —— 通过 payment 状态机创建后端订单并拉起支付。
 */
import { useEffect, useRef } from "react";

import {
  usePaymentDispatch,
  usePaymentState,
} from "@/stores/payment/payment-context";

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

export interface SubscriptionCheckoutButtonProps {
  /** 是否可用（未选套餐 / 未勾选协议 → false） */
  disabled?: boolean;
}

export function SubscriptionCheckoutButton({
  disabled = false,
}: SubscriptionCheckoutButtonProps) {
  const payment = usePaymentState();
  const paymentDispatch = usePaymentDispatch();
  const launchedNonceRef = useRef(0);

  useEffect(() => {
    if (!payment.payParams || payment.launchNonce <= launchedNonceRef.current) {
      return;
    }

    launchedNonceRef.current = payment.launchNonce;
    const paymentUrl = getPaymentUrl(payment.payParams);
    if (!paymentUrl) {
      paymentDispatch({
        type: "PaymentLaunchFailed",
        errorMessage: "Payment parameters did not include a supported URL.",
      });
      return;
    }

    window.location.href = paymentUrl;
  }, [payment.launchNonce, payment.payParams, paymentDispatch]);

  const isLoading =
    payment.isCreatingOrder ||
    payment.isPollingOrder ||
    payment.isCheckingVipStatus;
  const label = payment.isPaid
    ? "Activated"
    : payment.isPollingOrder
      ? "Processing payment..."
      : payment.isCreatingOrder
        ? "Creating order..."
        : "Confirm the agreement and Activate";

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

  return (
    <>
      <SubscriptionCtaButton
        type="button"
        disabled={disabled}
        isLoading={isLoading}
        onClick={handleClick}
        className={styles.button}
      >
        {label}
      </SubscriptionCtaButton>
      {payment.errorMessage ? (
        <p
          role="alert"
          style={{
            color: "#c0392b",
            fontSize: "0.875rem",
            marginTop: "0.5rem",
            textAlign: "center",
          }}
        >
          {payment.errorMessage}
        </p>
      ) : null}
    </>
  );
}

function getPaymentUrl(payParams: Record<string, unknown>): string | null {
  const keys = [
    "url",
    "checkoutUrl",
    "checkout_url",
    "paymentUrl",
    "payment_url",
    "redirectUrl",
    "redirect_url",
  ];

  for (const key of keys) {
    const value = payParams[key];
    if (typeof value === "string" && value.length > 0) return value;
  }

  return null;
}
