import { Badge, Box, Divider, Group, Modal, Stack, Text, ThemeIcon } from "@mantine/core";
import {
  Building2,
  Container as ContainerIcon,
  Fuel,
  MapPin,
  Package,
  TrainFront,
  Weight,
} from "lucide-react";
import type { TrainScheduleDetail } from "@/types/trainScheduling";
import { freightBrand } from "@/theme/freight-brand";

type Wagon = NonNullable<TrainScheduleDetail["trainSet"]>["wagons"][number];

export interface BookingDetailData {
  bookingId: string;
  reference: string | null;
  company: string | null;
  freightType: string | null;
  weightTons: number | null;
  status: string | null;
  priorityScore?: number | null;
}

interface BookingDetailModalProps {
  opened: boolean;
  onClose: () => void;
  booking: BookingDetailData | null;
  /** All wagons in the consist — used to show where this booking sits. */
  wagons: Wagon[];
}

function InfoRow({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: React.ReactNode;
}) {
  return (
    <Group justify="space-between" wrap="nowrap" gap="md">
      <Group gap={8} wrap="nowrap">
        <ThemeIcon size={28} radius="md" variant="light" color="edr-green">
          {icon}
        </ThemeIcon>
        <Text size="sm" c="dimmed">
          {label}
        </Text>
      </Group>
      <Box style={{ textAlign: "right" }}>{value}</Box>
    </Group>
  );
}

export const BookingDetailModal = ({
  opened,
  onClose,
  booking,
  wagons,
}: BookingDetailModalProps) => {
  if (!booking) return null;

  const bookingWagons = wagons.filter((w) =>
    (w.allocations ?? []).some((a) => a.bookingId === booking.bookingId),
  );
  const allocations = bookingWagons.flatMap((w) =>
    (w.allocations ?? [])
      .filter((a) => a.bookingId === booking.bookingId)
      .map((a) => ({ wagon: w, allocation: a })),
  );
  const containers = allocations.flatMap(({ allocation }) => allocation.containerItems ?? []);
  const isBulk = allocations.some(({ allocation }) =>
    (allocation.loadType ?? "").toUpperCase().includes("BULK"),
  );

  return (
    <Modal
      opened={opened}
      onClose={onClose}
      centered
      size="md"
      radius="lg"
      title={
        <Group gap={10} wrap="nowrap">
          <Box
            style={{
              width: 38,
              height: 38,
              borderRadius: 10,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              background: freightBrand.gradient,
              color: "white",
            }}
          >
            <Package size={20} />
          </Box>
          <div>
            <Text fw={800}>{booking.reference ?? "Booking"}</Text>
            <Text size="xs" c="dimmed">
              Booking details
            </Text>
          </div>
        </Group>
      }
    >
      <Stack gap="md">
        <Stack gap="sm">
          {booking.company ? (
            <InfoRow
              icon={<Building2 size={15} />}
              label="Company"
              value={
                <Text size="sm" fw={700}>
                  {booking.company}
                </Text>
              }
            />
          ) : null}
          <InfoRow
            icon={isBulk ? <Fuel size={15} /> : <ContainerIcon size={15} />}
            label="Freight type"
            value={
              <Badge variant="light" color={isBulk ? "orange" : "cyan"}>
                {booking.freightType ?? (isBulk ? "BULK" : "CONTAINER")}
              </Badge>
            }
          />
          <InfoRow
            icon={<Weight size={15} />}
            label="Weight"
            value={
              <Text size="sm" fw={700}>
                {booking.weightTons != null ? `${booking.weightTons.toFixed(1)} T` : "—"}
              </Text>
            }
          />
          <InfoRow
            icon={<TrainFront size={15} />}
            label="Wagons"
            value={
              bookingWagons.length ? (
                <Group gap={4} justify="flex-end">
                  {bookingWagons.map((w) => (
                    <Badge key={w.id} size="sm" variant="outline" color="edr-green" radius="sm">
                      #{w.sequenceNo}
                    </Badge>
                  ))}
                </Group>
              ) : (
                <Text size="sm" c="dimmed">
                  Not assigned to a wagon
                </Text>
              )
            }
          />
          {booking.status ? (
            <InfoRow
              icon={<MapPin size={15} />}
              label="Status"
              value={
                <Badge variant="light" color="gray">
                  {booking.status}
                </Badge>
              }
            />
          ) : null}
        </Stack>

        {containers.length ? (
          <>
            <Divider
              label={
                <Group gap={6}>
                  <ContainerIcon size={13} />
                  <Text size="xs" fw={700}>
                    Containers ({containers.length})
                  </Text>
                </Group>
              }
            />
            <Stack gap={6}>
              {containers.map((c, i) => (
                <Group
                  key={c.id}
                  justify="space-between"
                  wrap="nowrap"
                  p="xs"
                  style={{
                    borderRadius: 8,
                    background: "var(--mantine-color-gray-0)",
                    border: "1px solid var(--mantine-color-gray-2)",
                  }}
                >
                  <Group gap={8} wrap="nowrap">
                    <ContainerIcon size={14} color="var(--mantine-color-cyan-7)" />
                    <Text size="sm" fw={600}>
                      {c.containerNumber?.trim() || `Container ${i + 1}`}
                    </Text>
                  </Group>
                  {c.grossWeightTons != null ? (
                    <Text size="xs" c="dimmed">
                      {Number(c.grossWeightTons).toFixed(1)} T
                    </Text>
                  ) : null}
                </Group>
              ))}
            </Stack>
          </>
        ) : null}
      </Stack>
    </Modal>
  );
};
