import { Button, type ButtonProps } from "@mantine/core";
import { CreditCard } from "lucide-react";

import { Freight } from "@edr/types";

import { PaymentMethodModal } from "../BookingDetailPage/components/PaymentMethodModal";
import { priceTotal } from "../BookingDetailPage/utils";
import { useBookingPayment } from "./useBookingPayment";

interface PayNowButtonProps {
  booking: Freight.IBooking;
  label?: string;
  size?: ButtonProps["size"];
  fullWidth?: boolean;
}

/**
 * Self-contained "Pay now" action: shows the payment-method modal in place
 * instead of navigating to the booking detail page. Drop it into list rows,
 * cards, or anywhere a payable booking surfaces.
 */
export function PayNowButton({
  booking,
  label = "Pay now",
  size = "xs",
  fullWidth,
}: PayNowButtonProps) {
  const pay = useBookingPayment(booking.id);
  const pricing = booking.pricingBreakdown;

  return (
    <>
      <Button
        size={size}
        radius="md"
        fw={700}
        fz={13}
        color="edr-green"
        fullWidth={fullWidth}
        leftSection={<CreditCard size={14} />}
        onClick={(e) => {
          // Don't let a surrounding row-click handler fire.
          e.stopPropagation();
          pay.open();
        }}
      >
        {label}
      </Button>

      <PaymentMethodModal
        opened={pay.modalOpen}
        onClose={pay.close}
        amountLabel={pricing ? priceTotal(pricing) : undefined}
        currency={pricing?.currency ?? booking.paymentCurrency}
        processing={pay.processing}
        error={pay.error}
        onConfirm={pay.confirm}
      />
    </>
  );
}
