"use client";

import { useCallback } from "react";
import type { Stripe, StripeElements } from "@stripe/stripe-js";
import { mapStripeErrorMessage } from "./paymentStatus";

export interface ConfirmStripePaymentParams {
  stripe: Stripe | null;
  elements: StripeElements | null;
  clientSecret: string;
  returnUrl: string;
}

export interface ConfirmStripePaymentResult {
  ok: boolean;
  error?: string;
  redirecting?: boolean;
}

/**
 * Confirms PaymentIntent or SetupIntent via Payment Element.
 */
export function useStripePaymentConfirm() {
  const confirm = useCallback(
    async ({
      stripe,
      elements,
      clientSecret,
      returnUrl,
    }: ConfirmStripePaymentParams): Promise<ConfirmStripePaymentResult> => {
      if (!stripe || !elements) {
        return { ok: false, error: "Payment system not ready" };
      }

      const isSetupIntent = clientSecret.startsWith("seti_");

      if (isSetupIntent) {
        const { error } = await stripe.confirmSetup({
          elements,
          confirmParams: { return_url: returnUrl },
          redirect: "if_required",
        });

        if (error) {
          if (error.type === "card_error" || error.type === "validation_error") {
            return { ok: false, error: mapStripeErrorMessage(error) };
          }
          return { ok: false, error: mapStripeErrorMessage(error), redirecting: true };
        }

        return { ok: true };
      }

      const { error, paymentIntent } = await stripe.confirmPayment({
        elements,
        confirmParams: { return_url: returnUrl },
        redirect: "if_required",
      });

      if (error) {
        if (error.type === "card_error" || error.type === "validation_error") {
          return { ok: false, error: mapStripeErrorMessage(error) };
        }
        return { ok: false, error: mapStripeErrorMessage(error), redirecting: true };
      }

      if (paymentIntent?.status === "processing") {
        return { ok: true, redirecting: true };
      }

      if (paymentIntent?.status === "requires_action") {
        return { ok: false, error: "Additional authentication is required.", redirecting: true };
      }

      return { ok: true };
    },
    []
  );

  return { confirm };
}
