import { Anchor, Box, SimpleGrid, Text } from "@mantine/core";
import type { ReactNode } from "react";
import { Link } from "react-router-dom";

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

import { paymentStatusLabel } from "@/pages/bookings/booking-display";

import { fmtDate, yardLabel } from "../utils";
import { SectionCard } from "./layout";

type BookingLike = Freight.IBooking & {
  bookingType?: string;
  paymentStatus?: string;
  trainScheduleId?: string | null;
};

function Fact({ label, value }: { label: string; value: ReactNode }) {
  return (
    <Box miw={0}>
      <Text
        fz="11px"
        fw={700}
        c="#6B7C8E"
        tt="uppercase"
        style={{ letterSpacing: "0.06em" }}
      >
        {label}
      </Text>
      <Text mt={4} fz="15px" fw={700} c="#10202F" truncate>
        {value}
      </Text>
    </Box>
  );
}

/**
 * Compact at-a-glance facts strip at the top of the booking detail page — gives
 * a fast scan of the key attributes before the deeper cards below.
 */
export function KeyFactsStrip({ booking }: { booking: BookingLike }) {
  const isContract = booking.bookingType === "GENERAL_CONTRACT";
  // A drawdown under a GENERAL contract stays bookingType = ONE_TIME; its
  // "General" nature lives in the denormalized contractKind.
  const isGeneralDrawdown = !isContract && booking.contractKind === "GENERAL";
  const freight = booking.freightType === "BULK" ? "Bulk" : "Container";
  const payment = paymentStatusLabel(booking.paymentStatus);

  return (
    <SectionCard p="lg">
      <SimpleGrid cols={{ base: 2, md: 3, xl: 6 }} spacing={0} verticalSpacing="lg">
        <Fact
          label="Type"
          value={
            isContract
              ? "General Contract"
              : isGeneralDrawdown
                ? "General"
                : "One-Time"
          }
        />
        <Fact label="Cargo" value={freight} />
        {booking.contractId ? (
          <Fact
            label="Contract"
            value={
              <Anchor
                component={Link}
                to={`/contracts/${booking.contractId}`}
                fz="15px"
                fw={700}
                underline="hover"
              >
                {booking.contractReference ?? "View contract"}
              </Anchor>
            }
          />
        ) : null}
        <Fact
          label="Route"
          value={`${yardLabel(booking.originYard)} → ${yardLabel(booking.destinationYard)}`}
        />
        <Fact label="Payment" value={payment} />
        <Fact
          label="Train"
          value={booking.trainScheduleId ? "Assigned" : "Not assigned"}
        />
        <Fact
          label={isContract ? "Ordering until" : "Scheduled"}
          value={
            isContract
              ? fmtDate(booking.expiresAt ?? null)
              : fmtDate(booking.scheduledDate)
          }
        />
      </SimpleGrid>
    </SectionCard>
  );
}
