import { useMutation } from "@tanstack/react-query";
import { useState } from "react";

import { api } from "@/services/api";
import {
  paymentsService,
  type PaymentMethod,
} from "@/services/payments.service";

/**
 * Shared payment flow for a single booking: opens the method modal, fires
 * POST /payments/initiate, and redirects the browser to the provider (or the
 * fallback checkout page). Reused by the booking detail page, the booking list,
 * and the home page so "Pay now" behaves identically everywhere.
 */
export function useBookingPayment(bookingId: string) {
  const [modalOpen, setModalOpen] = useState(false);

  const mutation = useMutation({
    mutationFn: (method: PaymentMethod) =>
      api.payments.initiate.call({ bookingId, method }),
    onSuccess: (data, method) => {
      const redirectUrl =
        data?.clientAction?.type === "REDIRECT" && data.clientAction.url
          ? data.clientAction.url
          : paymentsService.checkoutUrl({ bookingId, method });
      window.location.href = redirectUrl;
    },
  });

  const open = () => setModalOpen(true);

  const close = () => {
    if (!mutation.isPending) {
      setModalOpen(false);
      mutation.reset();
    }
  };

  const error = mutation.isError
    ? mutation.error instanceof Error
      ? mutation.error.message
      : "Could not start payment. Please try again."
    : null;

  return {
    modalOpen,
    open,
    close,
    processing: mutation.isPending,
    error,
    confirm: (method: PaymentMethod) => mutation.mutate(method),
  };
}
