"use client";
/**
 * 订阅页主屏幕
 *
 * 原始 Dart: lib/ui/subscription/...
 *
 * 布局（顶到底）：
 *   1. 顶部返回箭头
 *   2. 用户信息行
 *   3. 渐变横幅
 *   4. 三个套餐卡片
 *   5. 自动续费说明
 *   6. 权益列表卡片
 *   7. 主操作按钮
 *   8. 协议复选框
 */
import { useEffect, useMemo, useRef } from "react";

import { Checkbox, MobileShell } from "@/app/_components/core";
import { AppConstants } from "@/core/app_constants";
import type { PaymentPlan } from "@/data/dto/payment";
import { VIP_BENEFITS } from "@/data/constants/vip-benefits";
import {
  usePaymentDispatch,
  usePaymentState,
} from "@/stores/payment/payment-context";
import { useUserDispatch, useUserState } from "@/stores/user/user-context";

import {
  SubscriptionBackLink,
  SubscriptionBanner,
  SubscriptionBenefitsCard,
  SubscriptionCheckoutButton,
  SubscriptionCtaButton,
  SubscriptionPlanCard,
  SubscriptionUserRow,
} from "./components";
import styles from "./components/subscription-screen.module.css";
import type { SubscriptionPlanView } from "./components/subscription-plan-card";

const FALLBACK_USERNAME = "User name";

function isVipPlan(plan: PaymentPlan): boolean {
  return plan.orderType.startsWith("vip_") || plan.planId.startsWith("vip_");
}

function currencySymbol(currency: string): string {
  if (currency === "CNY") return "¥";
  if (currency === "USD") return "$";
  return `${currency} `;
}

function formatAmount(amountCents: number): string {
  return (amountCents / 100).toFixed(2).replace(/\.00$/, "");
}

function planCaption(plan: PaymentPlan): string {
  if (plan.vipDays === null) return "Lifetime";
  const perDay = plan.amountCents / 100 / Math.max(plan.vipDays, 1);
  return `${currencySymbol(plan.currency)}${perDay.toFixed(2)}/day`;
}

function toPlanView(plan: PaymentPlan, index: number): SubscriptionPlanView {
  return {
    id: plan.planId,
    name: plan.planName,
    price: formatAmount(plan.amountCents),
    originalPrice: null,
    perDay: planCaption(plan),
    highlight: plan.planId === "vip_monthly" || index === 0,
    currencySymbol: currencySymbol(plan.currency),
  };
}

export function SubscriptionScreen() {
  const user = useUserState();
  const userDispatch = useUserDispatch();
  const payment = usePaymentState();
  const paymentDispatch = usePaymentDispatch();
  const refreshedPaidOrderRef = useRef<string | null>(null);

  useEffect(() => {
    if (payment.status === "idle") {
      paymentDispatch({ type: "PaymentInit" });
    }
  }, [payment.status, paymentDispatch]);

  useEffect(() => {
    if (!payment.isPaid || !payment.currentOrderId) return;
    if (refreshedPaidOrderRef.current === payment.currentOrderId) return;
    refreshedPaidOrderRef.current = payment.currentOrderId;
    userDispatch({ type: "UserFetch" });
  }, [payment.currentOrderId, payment.isPaid, userDispatch]);

  const vipPlans = useMemo(
    () =>
      payment.plans
        .filter(isVipPlan)
        .map((plan, index) => toPlanView(plan, index)),
    [payment.plans],
  );

  const selectedPlan =
    vipPlans.find((plan) => plan.id === payment.selectedPlanId) ?? null;
  const isPaymentBusy =
    payment.isCreatingOrder ||
    payment.isPollingOrder ||
    payment.isCheckingVipStatus;
  const canActivate =
    selectedPlan !== null && payment.agreed && !isPaymentBusy;
  const isVip =
    user.currentUser?.isVip === true ||
    payment.vipStatus?.isVip === true ||
    payment.isPaid;

  const name = user.currentUser?.username ?? FALLBACK_USERNAME;
  const avatarUrl = user.currentUser?.avatarUrl ?? null;
  const autoRenewCaption = payment.autoRenew
    ? "It will automatically renew upon expiration, and can be canceled at any time"
    : "This plan is a one-time purchase and will not automatically renew";

  return (
    <MobileShell>
      <div className={styles.shell}>
        <header className={styles.header}>
          <SubscriptionBackLink className={styles.backSlot} />
        </header>

        <section className={styles.userSlot}>
          <SubscriptionUserRow name={name} avatarUrl={avatarUrl} />
        </section>

        <section className={styles.bannerSlot}>
          <SubscriptionBanner />
        </section>

        <section
          className={styles.plansRow}
          aria-label="Choose a subscription plan"
        >
          {vipPlans.length > 0 ? (
            vipPlans.map((plan, index) => (
              <SubscriptionPlanCard
                key={plan.id}
                plan={plan}
                gradientIndex={index}
                selected={payment.selectedPlanId === plan.id}
                onClick={() =>
                  paymentDispatch({
                    type: "PaymentPlanSelected",
                    planId: plan.id,
                  })
                }
              />
            ))
          ) : (
            <p className={styles.plansStatus}>
              {payment.isLoadingPlans
                ? "Loading membership plans..."
                : payment.errorMessage ?? "Membership plans are unavailable."}
            </p>
          )}
        </section>

        <p className={styles.autoRenewCaption}>{autoRenewCaption}</p>

        <section className={styles.benefitsSlot}>
          <SubscriptionBenefitsCard
            title="VIP Membership Benefits"
            items={VIP_BENEFITS}
          />
        </section>

        <div className={styles.ctaSlot}>
          {isVip ? (
            <SubscriptionCtaButton type="button" disabled>
              VIP Activated
            </SubscriptionCtaButton>
          ) : (
            <SubscriptionCheckoutButton
              disabled={!canActivate}
            />
          )}
        </div>

        <div className={styles.agreementSlot}>
          <Checkbox
            checked={payment.agreed}
            onChange={(agreed) =>
              paymentDispatch({
                type: "PaymentAgreementChanged",
                agreed,
              })
            }
            label={
              <>
                I agree to the{" "}
                <a
                  href={AppConstants.privacyPolicyUrl}
                  target="_blank"
                  rel="noreferrer"
                  className={styles.agreementLink}
                >
                  VIP Membership Benefits Agreement
                </a>{" "}
                and{" "}
                <a
                  href={AppConstants.termsOfServiceUrl}
                  target="_blank"
                  rel="noreferrer"
                  className={styles.agreementLink}
                >
                  Automatic renewal Agreement
                </a>
              </>
            }
          />
        </div>
      </div>
    </MobileShell>
  );
}
