"use client";

import { useEffect, useRef } from "react";

import type { PayChannel } from "@/data/schemas/payment";
import type { PaymentMethodConfig } from "@/lib/payment/payment_method";

export interface UsePaymentMethodSelectionInput {
  config: PaymentMethodConfig;
  currentPayChannel: PayChannel;
  isPaymentBusy: boolean;
  requestedPayChannel: PayChannel | null;
  onChange: (payChannel: PayChannel) => void;
}

export function usePaymentMethodSelection({
  config,
  currentPayChannel,
  isPaymentBusy,
  requestedPayChannel,
  onChange,
}: UsePaymentMethodSelectionInput): void {
  const appliedDefaultChannelRef = useRef<PayChannel | null>(null);

  useEffect(() => {
    if (isPaymentBusy) return;

    if (!config.canChoosePaymentMethod) {
      appliedDefaultChannelRef.current = null;
      if (currentPayChannel !== "stripe") onChange("stripe");
      return;
    }

    if (requestedPayChannel !== null) return;
    if (appliedDefaultChannelRef.current === config.initialPayChannel) return;
    appliedDefaultChannelRef.current = config.initialPayChannel;

    if (currentPayChannel !== config.initialPayChannel) {
      onChange(config.initialPayChannel);
    }
  }, [
    config.canChoosePaymentMethod,
    config.initialPayChannel,
    currentPayChannel,
    isPaymentBusy,
    onChange,
    requestedPayChannel,
  ]);
}
