"use client";

import { useCallback, useEffect, useRef } from "react";
import { useSession } from "next-auth/react";
import { usePaddle, CheckoutEventNames } from "./paddle-provider";
import type { PaddleEventData } from "./paddle-provider";
import { useCheckoutConfig } from "@/lib/api/subscriptions/use-hooks";
import type { PlanType, BillingInterval } from "@/lib/api/subscriptions/types";
import { useQueryClient } from "@tanstack/react-query";
import { SubscriptionQueryKeys } from "@/lib/api/subscriptions/use-hooks";

interface UsePaddleCheckoutReturn {
  startCheckout: (plan: PlanType, interval: BillingInterval) => Promise<void>;
  isLoading: boolean;
}

/**
 * Hook that orchestrates the Paddle checkout flow:
 * 1. Calls backend to get priceId + clientToken
 * 2. Opens Paddle overlay checkout
 * 3. Listens for Paddle checkout.completed event to invalidate subscription cache
 */
export function usePaddleCheckout(): UsePaddleCheckoutReturn {
  const { openCheckout, onCheckoutEvent } = usePaddle();
  const { data: session } = useSession();
  const checkoutConfig = useCheckoutConfig();
  const queryClient = useQueryClient();
  const isSubscribedRef = useRef(false);

  // Subscribe to Paddle events once on mount
  useEffect(() => {
    if (isSubscribedRef.current) return;
    isSubscribedRef.current = true;

    const unsubscribe = onCheckoutEvent((event: PaddleEventData) => {
      if (event.name === CheckoutEventNames.CHECKOUT_COMPLETED) {
        // Paddle confirmed the payment — refresh subscription state
        queryClient.invalidateQueries({
          queryKey: SubscriptionQueryKeys.me(),
        });
      }

      if (event.name === CheckoutEventNames.CHECKOUT_CLOSED) {
        // User closed checkout — refresh in case a payment was already processed
        queryClient.invalidateQueries({
          queryKey: SubscriptionQueryKeys.me(),
        });
      }
    });

    return () => {
      isSubscribedRef.current = false;
      unsubscribe();
    };
  }, [onCheckoutEvent, queryClient]);

  const startCheckout = useCallback(
    async (plan: PlanType, interval: BillingInterval) => {
      if (!session?.user?.email) {
        console.error("[Paddle] User not authenticated");
        return;
      }

      const result = await checkoutConfig.mutateAsync({
        plan,
        billingInterval: interval,
      });

      if (!result.success || !result.data) {
        console.error("[Paddle] Failed to get checkout config");
        return;
      }

      const { priceId } = result.data;

      openCheckout({
        items: [{ priceId, quantity: 1 }],
        customer: {
          email: session.user.email,
        },
        customData: {
          userId: session.user.id,
        },
        settings: {
          displayMode: "overlay",
          theme: "dark",
          locale: "tr",
          successUrl: `${window.location.origin}/profile?checkout=success`,
        },
      });
    },
    [openCheckout, session, checkoutConfig],
  );

  return {
    startCheckout,
    isLoading: checkoutConfig.isPending,
  };
}
