"use client";
import { useEffect, useMemo, useRef } from "react";

import { BackButton } from "@/app/_components";
import { Checkbox, MobileShell } from "@/app/_components/core";
import { AppConstants } from "@/core/app_constants";
import { useUserState } from "@/stores/user/user-context";

import {
  SubscriptionCheckoutButton,
  SubscriptionCoinsOfferSection,
  SubscriptionPaymentMethod,
  SubscriptionPaymentSuccessDialog,
  SubscriptionVipOfferSection,
} from "./components";
import styles from "./components/subscription-screen.module.css";
import {
  findSelectedSubscriptionPlan,
  getDefaultPayChannelForCountryCode,
  getDefaultSubscriptionPlanId,
  toCoinsOfferPlanViews,
  toVipOfferPlanViews,
  type SubscriptionType,
} from "./subscription-screen.helpers";
import { useSubscriptionPaymentFlow } from "./use-subscription-payment-flow";

export type { SubscriptionType } from "./subscription-screen.helpers";

export interface SubscriptionScreenProps {
  subscriptionType?: SubscriptionType;
  shouldResumePendingOrder?: boolean;
  returnTo?: "chat" | null;
}

export function SubscriptionScreen({
  subscriptionType = "vip",
  shouldResumePendingOrder = false,
  returnTo = null,
}: SubscriptionScreenProps) {
  const {
    payment,
    paymentDispatch,
    showPaymentSuccessDialog,
    handleBackClick,
    handlePaymentSuccessClose,
  } = useSubscriptionPaymentFlow({
    subscriptionType,
    shouldResumePendingOrder,
    returnTo,
  });
  const user = useUserState();
  const paymentMethodManuallySelectedRef = useRef(false);
  const canSubscribeVip = subscriptionType === "vip";

  const vipOfferPlans = useMemo(
    () => toVipOfferPlanViews(payment.plans),
    [payment.plans],
  );
  const directCoinsPlans = useMemo(
    () => toCoinsOfferPlanViews(payment.plans),
    [payment.plans],
  );

  const selectedPlan = findSelectedSubscriptionPlan({
    canSubscribeVip,
    selectedPlanId: payment.selectedPlanId,
    vipPlans: vipOfferPlans,
    coinPlans: directCoinsPlans,
  });
  const isPaymentBusy =
    payment.isCreatingOrder ||
    payment.isPollingOrder;
  const canActivate =
    selectedPlan !== null && payment.agreed && !isPaymentBusy;

  useEffect(() => {
    const defaultPlanId = getDefaultSubscriptionPlanId({
      canSubscribeVip,
      selectedPlanId: payment.selectedPlanId,
      status: payment.status,
      isLoadingPlans: payment.isLoadingPlans,
      selectedPlan,
      vipPlans: vipOfferPlans,
      coinPlans: directCoinsPlans,
    });
    if (!defaultPlanId) return;

    paymentDispatch({
      type: "PaymentPlanSelected",
      planId: defaultPlanId,
    });
  }, [
    canSubscribeVip,
    directCoinsPlans,
    payment.isLoadingPlans,
    paymentDispatch,
    payment.selectedPlanId,
    payment.status,
    selectedPlan,
    vipOfferPlans,
  ]);

  useEffect(() => {
    if (payment.status !== "ready") return;
    if (paymentMethodManuallySelectedRef.current) return;

    const countryCode = user.currentUser?.countryCode ?? "";
    if (countryCode.trim().length === 0) return;

    const defaultPayChannel =
      getDefaultPayChannelForCountryCode(countryCode);
    if (payment.payChannel === defaultPayChannel) return;

    paymentDispatch({
      type: "PaymentPayChannelChanged",
      payChannel: defaultPayChannel,
    });
  }, [
    payment.payChannel,
    payment.status,
    paymentDispatch,
    user.currentUser?.countryCode,
  ]);

  return (
    <MobileShell>
      <div className={styles.shell}>
        <header className={styles.header}>
          <BackButton
            className={styles.backSlot}
            onClick={handleBackClick}
            variant="soft"
          />
        </header>

        <div className={styles.offerStack}>
          {canSubscribeVip ? (
            <SubscriptionVipOfferSection
              plans={vipOfferPlans}
              selectedPlanId={payment.selectedPlanId || selectedPlan?.id || null}
              onSelectPlan={(planId) =>
                paymentDispatch({
                  type: "PaymentPlanSelected",
                  planId,
                })
              }
            />
          ) : null}
          <SubscriptionCoinsOfferSection
            plans={directCoinsPlans}
            selectedPlanId={payment.selectedPlanId || selectedPlan?.id || null}
            onSelectPlan={(planId) =>
              paymentDispatch({
                type: "PaymentPlanSelected",
                planId,
              })
            }
          />
        </div>

        <section className={styles.paymentMethodSlot}>
          <SubscriptionPaymentMethod
            value={payment.payChannel}
            disabled={isPaymentBusy}
            onChange={(payChannel) => {
              paymentMethodManuallySelectedRef.current = true;
              paymentDispatch({
                type: "PaymentPayChannelChanged",
                payChannel,
              });
            }}
          />
        </section>

        <div className={styles.ctaSlot}>
          <SubscriptionCheckoutButton
            disabled={!canActivate}
            subscriptionType={subscriptionType}
            returnTo={returnTo}
          />
        </div>

        <div className={styles.agreementSlot}>
          <Checkbox
            checked={payment.agreed}
            onChange={(agreed) =>
              paymentDispatch({
                type: "PaymentAgreementChanged",
                agreed,
              })
            }
            label={
              <span className={styles.agreementLabel}>
                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>
              </span>
            }
          />
        </div>

        <SubscriptionPaymentSuccessDialog
          open={showPaymentSuccessDialog}
          subscriptionType={subscriptionType}
          onClose={handlePaymentSuccessClose}
        />
      </div>
    </MobileShell>
  );
}
