import { Box, Group, Text } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { MoveRight } from "lucide-react";

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

import { contractsService } from "@/services/contracts.service";

import {
  ARRIVAL_STAGE,
  CONTRACT_ARRIVAL_STAGE,
  STATUS_MAP,
  resolveContractStage,
  resolveStage,
} from "../constants";
import { fmtDate, isDraftLike, isNegative, yardLabel } from "../utils";
import { JourneyWizard } from "./JourneyWizard";
import { SectionCard } from "./layout";

/** Origin → destination strip rendered above the progress tracker. */
function RouteStrip({ booking }: { booking: Freight.IBooking }) {
  const origin = yardLabel(booking.originYard);
  const destination = yardLabel(booking.destinationYard);
  return (
    <Box
      mb={22}
      px={18}
      py={14}
      style={{
        borderRadius: 12,
        border: "1px solid #E6ECF2",
      }}
    >
      <Group justify="space-between" align="center" wrap="nowrap" gap="md">
        <RouteEndpoint label="Origin" value={origin} />
        <MoveRight size={18} color="#6B7C8E" className="shrink-0" />
        <RouteEndpoint label="Destination" value={destination} alignRight />
      </Group>
    </Box>
  );
}

function RouteEndpoint({
  label,
  value,
  alignRight,
}: {
  label: string;
  value: string;
  alignRight?: boolean;
}) {
  return (
    <Box miw={0} style={{ textAlign: alignRight ? "right" : "left", flex: 1 }}>
      <Text
        fz="11px"
        fw={700}
        c="#6B7C8E"
        tt="uppercase"
        style={{ letterSpacing: "0.06em" }}
      >
        {label}
      </Text>
      <Text mt={3} fz="15px" fw={700} c="#10202F" truncate>
        {value}
      </Text>
    </Box>
  );
}

export function StatusHero({
  booking,
  children,
}: {
  booking: Freight.IBooking;
  children?: React.ReactNode;
}) {
  const status = booking.status;
  // Customs (Path B) bookings render the GL milestone rows inside the unified
  // wizard. Same query key the duty-slip panel uses, so the cache is shared.
  const { data: milestones = [] } = useQuery({
    queryKey: ["booking-milestones", booking.id],
    queryFn: () => contractsService.getBookingMilestones(booking.id),
    enabled: Boolean(booking.id) && Boolean(booking.customsClearingEnabled),
  });
  // Contract-drawdown bookings (initiated under a contract) follow a dedicated
  // wizard — initiated → submitted → accepted → payment → … — instead of the
  // direct booking's Request/Approval/Contract stages.
  const isContractDrawdown = Boolean(booking.contractId) && !isNegative(status);
  const arrivalStage = isContractDrawdown
    ? CONTRACT_ARRIVAL_STAGE
    : ARRIVAL_STAGE;
  const stage = isContractDrawdown
    ? resolveContractStage(booking)
    : resolveStage(booking);
  // Contract-drawdown instance in the clearance gate: it was INITIATED with one
  // click (no cargo/date yet), not submitted through the wizard.
  const isInitiatedInstance =
    status === "AWAITING_DOCUMENTS" && Boolean(booking.contractId);
  // Legacy bookings never reach the ARRIVED status — they light up the Arrival
  // stage from the train's ARRIVED state while staying IN_TRANSIT, so the
  // headline is overridden here. Bookings with a per-booking journey carry the
  // ARRIVED status themselves and use its own STATUS_MAP copy.
  const cfg =
    stage === arrivalStage && STATUS_MAP[status]?.stage !== ARRIVAL_STAGE
      ? {
          title: "Train arrived at destination",
          description:
            "Your shipment reached its destination yard and is being unloaded and prepared for release.",
          stage,
        }
      : isInitiatedInstance
        ? {
            title: "Upload clearance documents",
            description:
              "Upload the required clearance documents to start the review. Once the review is finalized you can book your shipment.",
            stage,
          }
        : isContractDrawdown && status === "FULLY_EXECUTED"
          ? {
              title: "Accepted by operations",
              description:
                "Operations accepted your order. Complete payment once your train is selected to secure the slot.",
              stage,
            }
          : (STATUS_MAP[status] ?? STATUS_MAP.DRAFT);
  const negative = isNegative(status);
  const draft = isDraftLike(status);

  const chipLabel = draft ? "Last edited" : negative ? "Updated" : "Scheduled";
  const chipValue = fmtDate(
    draft || negative ? booking.updatedAt : booking.scheduledDate,
  );

  return (
    <SectionCard p={28}>
      <Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
        <Box>
          <Text fz="21px" fw={800} c="#10202F">
            {cfg.title}
          </Text>
          <Text mt={5} fz="14px" c="#6B7C8E">
            {cfg.description}
          </Text>
        </Box>
        <Box ta="right">
          <Text
            fz="11px"
            fw={700}
            c="#6B7C8E"
            tt="uppercase"
            style={{ letterSpacing: "0.06em" }}
          >
            {chipLabel}
          </Text>
          <Text mt={3} fz="sm" fw={700} c="#10202F">
            {chipValue}
          </Text>
        </Box>
      </Group>

      <Box my={26} h={1} w="100%" bg="#EEF2F6" />

      {!negative && <RouteStrip booking={booking} />}

      {children ?? (
        <JourneyWizard booking={booking} milestones={milestones} />
      )}
    </SectionCard>
  );
}
