import { Box, Button, Group, Modal, Text } from "@mantine/core";
import { CheckCircle2, PackagePlus, Upload } from "lucide-react";
import { useNavigate } from "react-router-dom";

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

import { ClearanceFlow } from "./ClearanceFlow";
import { getBookingNextAction } from "./bookingNextAction";
import { useClearanceFlow } from "./useClearanceFlow";

interface BookingActionModalProps {
  booking: Freight.IBooking;
  opened: boolean;
  onClose: () => void;
}

/**
 * Home-page action modal: runs the full clearance / operation flow for a single
 * booking without leaving the My Shipments list. The customer can upload the
 * required documents, re-upload queried ones, then pick a shipment day and
 * proceed to operation — all in place.
 *
 * Mounted only while `opened` so the clearance grid is fetched lazily and the
 * staged-upload state resets every time the customer reopens it.
 */
export function BookingActionModal({
  booking,
  opened,
  onClose,
}: BookingActionModalProps) {
  if (!opened) return null;
  return <BookingActionModalBody booking={booking} onClose={onClose} />;
}

function BookingActionModalBody({
  booking,
  onClose,
}: {
  booking: Freight.IBooking;
  onClose: () => void;
}) {
  const action = getBookingNextAction(booking);
  const flow = useClearanceFlow(booking);
  const navigate = useNavigate();
  const reference = booking.reference;

  const handleSubmit = () => flow.submitDocuments({ onSuccess: onClose });
  const handleProceed = () => flow.proceedToOperation({ onSuccess: onClose });

  return (
    // Sized and styled to match the contract clearance modal
    // (ContractClearanceAction) so both flows read as the same surface.
    <Modal
      opened
      onClose={onClose}
      centered
      size="xl"
      radius="md"
      title={
        <Box>
          <Text fw={700} fz={16}>
            {action?.title ?? "Clearance documents"}
          </Text>
          <Text fz={12} c="dimmed" ff="monospace">
            {reference}
          </Text>
        </Box>
      }
      overlayProps={{ blur: 2, backgroundOpacity: 0.55 }}
      styles={{ body: { paddingTop: 8 } }}
    >
      {flow.isLoading || !flow.clearance ? (
        <Text fz="13px" c="dimmed" py="md">
          Loading clearance…
        </Text>
      ) : (
        <ClearanceFlow
          booking={booking}
          flow={flow}
          footer={
            <Group justify="flex-end" mt="xl" gap="sm">
              <Button variant="default" radius="md" onClick={onClose}>
                Close
              </Button>
              {flow.canUpload && (
                <Button
                  color="edr-green"
                  radius="md"
                  leftSection={<Upload size={16} />}
                  onClick={handleSubmit}
                  loading={flow.uploadMutation.isPending}
                  disabled={!flow.canSubmit}
                >
                  Submit documents
                </Button>
              )}
              {flow.needsCompletion && flow.completeTo ? (
                <Button
                  color="edr-green"
                  radius="md"
                  leftSection={<PackagePlus size={16} />}
                  onClick={() => {
                    onClose();
                    navigate(flow.completeTo!);
                  }}
                >
                  Complete booking
                </Button>
              ) : (
                // Customs bare instances await GL completion — no customer
                // proceed button (the server rejects it anyway).
                flow.isReady &&
                !flow.awaitingGlCompletion && (
                  <Button
                    color="edr-green"
                    radius="md"
                    leftSection={<CheckCircle2 size={16} />}
                    onClick={handleProceed}
                    loading={flow.proceedMutation.isPending}
                    disabled={!flow.scheduledDate}
                  >
                    Proceed to operation
                  </Button>
                )
              )}
            </Group>
          }
        />
      )}
    </Modal>
  );
}
