import React, { createContext, useContext } from "react";
import { getOrganizationUpgradeBlockReason, type UpgradeBlockReason } from "../hooks/stripe";
import { useOrganization } from "../hooks/organization";
import { useMaybeUser } from "../providers/UserStoreProvider";

interface UpgradeBlockContextValue {
  isBlocked: boolean;
  reason: UpgradeBlockReason | null;
}

const UpgradeBlockContext = createContext<UpgradeBlockContextValue | null>(null);

export const useUpgradeBlock = () => {
  const context = useContext(UpgradeBlockContext);
  if (!context) {
    throw new Error("useUpgradeBlock must be used within UpgradeBlockProvider");
  }
  return context;
};

export const useMaybeUpgradeBlock = () => useContext(UpgradeBlockContext);

interface UpgradeBlockProviderProps {
  children: React.ReactNode;
}

export const UpgradeBlockProvider: React.FC<UpgradeBlockProviderProps> = ({ children }) => {
  const { data: organizationData } = useOrganization();
  const user = useMaybeUser();

  // Wait for both user and organization data before deciding.
  // Temporary users are never blocked — they have read-only access enforced at the API level.
  const reason =
    !user || !organizationData
      ? null
      : user.is_temporary
        ? null
        : getOrganizationUpgradeBlockReason({
            is_trial_expired: organizationData.is_trial_expired,
            required_plan: organizationData.required_plan,
            required_team_quantity: organizationData.required_team_quantity,
            active_subscription_plan: organizationData.active_subscription_plan,
            active_subscription_quantity: organizationData.active_subscription_quantity,
          });

  const isBlocked = reason !== null;

  return (
    <UpgradeBlockContext.Provider value={{ isBlocked, reason }}>
      {children}
    </UpgradeBlockContext.Provider>
  );
};
