import { useEffect, useRef } from "react";
import { useOrganization } from "../hooks/organization";
import { useCreateCheckoutSession } from "../hooks/stripe";
import {
  PENDING_BILLING_CHECKOUT_PLAN_KEY,
  isSignupBillingIntent,
  satisfiesPendingCheckoutPlan,
} from "../lib/billing";
import { useMaybeUser } from "../providers/UserStoreProvider";

export function PendingSignupCheckout() {
  const user = useMaybeUser();
  const { data: organizationData, isLoading } = useOrganization();
  const { mutate: createCheckout } = useCreateCheckoutSession();
  const hasTriggered = useRef(false);

  useEffect(() => {
    if (hasTriggered.current) return;
    if (!user || isLoading || !organizationData) return;

    const pendingCheckoutValue = localStorage.getItem(PENDING_BILLING_CHECKOUT_PLAN_KEY);
    if (!isSignupBillingIntent(pendingCheckoutValue)) {
      if (pendingCheckoutValue) {
        localStorage.removeItem(PENDING_BILLING_CHECKOUT_PLAN_KEY);
      }
      return;
    }

    if (
      satisfiesPendingCheckoutPlan(pendingCheckoutValue, organizationData.active_subscription_plan)
    ) {
      localStorage.removeItem(PENDING_BILLING_CHECKOUT_PLAN_KEY);
      return;
    }

    if (!organizationData.is_billing_owner) {
      return;
    }

    hasTriggered.current = true;
    localStorage.removeItem(PENDING_BILLING_CHECKOUT_PLAN_KEY);
    createCheckout(
      {
        plan: pendingCheckoutValue,
        successUrl: `${window.location.origin}/settings?success=true`,
        cancelUrl: `${window.location.origin}/settings?canceled=true`,
      },
      {
        onError: () => {
          localStorage.setItem(PENDING_BILLING_CHECKOUT_PLAN_KEY, pendingCheckoutValue);
          hasTriggered.current = false;
        },
      }
    );
  }, [createCheckout, isLoading, organizationData, user]);

  return null;
}
