"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { shallowEqual } from "@xstate/react";

import type { LoginStatus } from "@/data/schemas/auth";
import { getDefaultPayChannelForCountryCode } from "@/lib/payment/default_pay_channel";
import { useAppNavigator } from "@/router/use-app-navigator";
import {
  usePaymentDispatch,
  usePaymentSelector,
} from "@/stores/payment/payment-context";
import { useUserSelector } from "@/stores/user/user-context";

import { deriveChatSupportCta } from "../chat-support-cta";

export function useChatSupportCta(input: {
  characterId: string;
  historyLoaded: boolean;
  loginStatus: LoginStatus;
}) {
  const navigator = useAppNavigator();
  const paymentDispatch = usePaymentDispatch();
  const initializedCharacterRef = useRef<string | null>(null);
  const [nowMs, setNowMs] = useState(() => Date.now());
  const payment = usePaymentSelector(
    (state) => ({
      commercialOffer: state.context.commercialOffer,
      isFirstRecharge: state.context.isFirstRecharge,
      supportCharacterId: state.context.supportCharacterId,
    }),
    shallowEqual,
  );
  const countryCode = useUserSelector(
    (state) => state.context.currentUser?.countryCode,
  );
  const isAuthenticated =
    input.loginStatus !== "notLoggedIn" && input.loginStatus !== "guest";

  useEffect(() => {
    if (!isAuthenticated) return;
    if (initializedCharacterRef.current === input.characterId) return;
    initializedCharacterRef.current = input.characterId;
    paymentDispatch({
      type: "PaymentInit",
      characterId: input.characterId,
      payChannel: getDefaultPayChannelForCountryCode(countryCode),
    });
  }, [countryCode, input.characterId, isAuthenticated, paymentDispatch]);

  useEffect(() => {
    if (!payment.commercialOffer) return;
    const timer = window.setInterval(() => setNowMs(Date.now()), 1000);
    return () => window.clearInterval(timer);
  }, [payment.commercialOffer]);

  const cta = useMemo(
    () =>
      deriveChatSupportCta({
        isFirstRecharge:
          isAuthenticated && payment.supportCharacterId === input.characterId
            ? payment.isFirstRecharge
            : false,
        commercialOffer:
          isAuthenticated && payment.supportCharacterId === input.characterId
            ? payment.commercialOffer
            : null,
        nowMs,
      }),
    [
      input.characterId,
      isAuthenticated,
      nowMs,
      payment.commercialOffer,
      payment.isFirstRecharge,
      payment.supportCharacterId,
    ],
  );

  const open = () => {
    navigator.openSubscription({
      type: cta.planId?.startsWith("dol_") ? "topup" : "vip",
      returnTo: "chat",
      ...(cta.planId ? { planId: cta.planId } : {}),
      ...(cta.commercialOfferId
        ? { commercialOfferId: cta.commercialOfferId }
        : {}),
      analytics: {
        entryPoint: "chat_offer_banner",
        triggerReason:
          cta.kind === "support" ? "vip_cta" : "commercial_offer",
      },
    });
  };

  return { ...cta, visible: input.historyLoaded, open };
}
