"use client";

import { useEffect, useRef, useState } from "react";

import { usePaymentOrderLifecycle } from "@/app/_hooks/use-payment-order-lifecycle";
import { useAppNavigator } from "@/router/use-app-navigator";
import {
  usePaymentDispatch,
  usePaymentState,
} from "@/stores/payment/payment-context";
import type { PayChannel } from "@/data/dto/payment";

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

export interface UseSubscriptionPaymentFlowInput {
  subscriptionType: SubscriptionType;
  shouldResumePendingOrder: boolean;
  returnTo: "chat" | null;
  initialPayChannel: PayChannel;
}

export function useSubscriptionPaymentFlow({
  subscriptionType,
  shouldResumePendingOrder,
  returnTo,
  initialPayChannel,
}: UseSubscriptionPaymentFlowInput) {
  const navigator = useAppNavigator();
  const payment = usePaymentState();
  const paymentDispatch = usePaymentDispatch();
  const successDialogShownOrderRef = useRef<string | null>(null);
  const initialPayChannelAppliedRef = useRef(false);
  const [showPaymentSuccessDialog, setShowPaymentSuccessDialog] =
    useState(false);

  usePaymentOrderLifecycle({
    payment,
    paymentDispatch,
    paymentType: subscriptionType,
    shouldResumePendingOrder,
  });

  useEffect(() => {
    if (payment.status === "idle") {
      initialPayChannelAppliedRef.current = true;
      paymentDispatch({
        type: "PaymentInit",
        payChannel: initialPayChannel,
      });
      return;
    }

    if (
      !initialPayChannelAppliedRef.current &&
      payment.status === "ready"
    ) {
      initialPayChannelAppliedRef.current = true;
      if (payment.payChannel === initialPayChannel) return;
      paymentDispatch({
        type: "PaymentPayChannelChanged",
        payChannel: initialPayChannel,
      });
    }
  }, [
    initialPayChannel,
    payment.payChannel,
    payment.status,
    paymentDispatch,
  ]);

  useEffect(() => {
    if (!payment.isPaid || !payment.currentOrderId) return;
    if (successDialogShownOrderRef.current === payment.currentOrderId) return;

    successDialogShownOrderRef.current = payment.currentOrderId;
    setShowPaymentSuccessDialog(true);
  }, [payment.currentOrderId, payment.isPaid]);

  const handleBackClick = () => {
    navigator.exitSubscription(returnTo);
  };

  const handlePaymentSuccessClose = () => {
    setShowPaymentSuccessDialog(false);
    paymentDispatch({ type: "PaymentReset" });
    navigator.exitSubscriptionAfterSuccess(returnTo);
  };

  return {
    payment,
    paymentDispatch,
    showPaymentSuccessDialog,
    handleBackClick,
    handlePaymentSuccessClose,
  };
}
