/**
 * useOfferCheckout — what a plan button does, wherever plans are listed
 * (pricing page, upgrade modal, billing settings):
 *   signed out  → onSignedOut(offer) (the app sends them to sign up and back)
 *   free plan   → enrol, then billing ("scheduled" when it ends a paid plan)
 *   paid plan   → hosted checkout, or an in-place change (afterCheckout)
 *
 * Returns "navigating" once the browser is being sent away, so plan buttons
 * stay disabled until the page unloads. Must be inside a <BillingProvider>.
 */

import { useCallback, useState } from "react";
import type { PlanChangePreview, ProductOffer } from "../types";
import { afterCheckout, withSessionPlaceholder, type CheckoutPaths } from "../utils/checkout-flow";
import { useCheckout } from "./useCheckout";

export interface UseOfferCheckoutOptions {
  isAuthenticated: boolean;
  /** Same-origin path to land on after paying (already through safeNextPath). */
  nextPath?: string | null;
  /** Path to come back to when checkout is cancelled. */
  cancelPath: string;
  /** Absolute return URL for a path, using the app's public origin. */
  returnUrl: (path: string) => string;
  /** Default `window.location.assign`. */
  navigate?: (url: string) => void;
  /** Signed out: send the person to sign up and back to this offer. */
  onSignedOut: (offer: ProductOffer) => void;
  /** A paid checkout is about to start (analytics). */
  onBeginCheckout?: (offer: ProductOffer) => void;
  /** Defaults: /settings/billing[?status=success|scheduled]. */
  paths?: Partial<CheckoutPaths>;
}

export function useOfferCheckout(options: UseOfferCheckoutOptions) {
  const { isAuthenticated, nextPath = null, cancelPath, returnUrl, navigate, onSignedOut, onBeginCheckout } = options;
  const billingPath = options.paths?.billingPath ?? "/settings/billing";
  const successPath = options.paths?.successPath ?? `${billingPath}?status=success`;
  const scheduledPath = options.paths?.scheduledPath ?? `${billingPath}?status=scheduled`;
  const { checkout, subscribeFree } = useCheckout();
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const selectOffer = useCallback(
    async (offer: ProductOffer, _preview?: PlanChangePreview | null): Promise<"navigating" | void> => {
      const go = navigate ?? ((u: string) => window.location.assign(u));
      if (!isAuthenticated) {
        onSignedOut(offer);
        return "navigating";
      }
      setError(null);
      setLoading(true);
      try {
        if (offer.isFree) {
          const result = await subscribeFree(offer.id);
          go(result?.scheduled_downgrade ? scheduledPath : successPath);
          return "navigating";
        }
        onBeginCheckout?.(offer);
        const result = await checkout({
          offerId: offer.id,
          successUrl: nextPath ? returnUrl(nextPath) : withSessionPlaceholder(returnUrl(successPath)),
          cancelUrl: returnUrl(cancelPath),
        });
        const destination = afterCheckout(result, nextPath, { billingPath, successPath, scheduledPath });
        if (destination) {
          go(destination);
          return "navigating";
        }
        setError("Unable to start checkout. Please try again.");
        setLoading(false);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Something went wrong. Please try again.");
        setLoading(false);
      }
    },
    [isAuthenticated, nextPath, cancelPath, returnUrl, navigate, onSignedOut, onBeginCheckout,
      billingPath, successPath, scheduledPath, checkout, subscribeFree],
  );

  return { selectOffer, error, loading };
}
