import { Button } from "@mantine/core";
import { FileSignature } from "lucide-react";
import { useNavigate } from "react-router-dom";

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

/**
 * Statuses where the contract is ready for the customer to review and sign.
 * These are the only states where {@link ContractSignButton} renders — once the
 * customer has signed, the row falls back to its normal "View" action.
 */
const SIGNABLE_STATUSES = ["CONTRACT_READY", "APPROVED_PENDING_SIGNATURE"];

export function bookingIsSignable(
  booking: Pick<Freight.IBooking, "status">,
): boolean {
  return SIGNABLE_STATUSES.includes(booking.status as string);
}

interface ContractSignButtonProps {
  booking: Freight.IBooking;
  size?: "xs" | "sm";
}

/**
 * Self-contained "View & Sign" trigger for a My Shipments row. Renders nothing
 * unless the booking's contract is ready to be signed; otherwise shows a button
 * that navigates to the full-page contract viewer ({@link BookingContractPage})
 * where the signature flow lives.
 *
 * Drop it into a list row exactly like {@link PayNowButton} — it stops click
 * propagation so it never triggers the row's navigation handler.
 */
export function ContractSignButton({
  booking,
  size = "sm",
}: ContractSignButtonProps) {
  const navigate = useNavigate();

  if (!bookingIsSignable(booking)) return null;

  return (
    <Button
      size={size}
      radius="md"
      fw={700}
      fz={13}
      color="edr-green"
      leftSection={<FileSignature size={14} />}
      onClick={(e) => {
        // Don't let the surrounding row-click handler fire.
        e.stopPropagation();
        navigate(`/bookings/${booking.id}/contract`);
      }}
    >
      View &amp; sign
    </Button>
  );
}
