import { Box, Group, Table, Text } from "@mantine/core";
import { AlertTriangle, Flame, Snowflake, Undo2 } from "lucide-react";
import type { ReactNode } from "react";

import type {
  BookingContainerLineDetail,
  BookingContainerUnitDetail,
  BookingDetail,
} from "../booking-detail-types";
import { fmtWeight, totalVgmTons } from "../utils";
import { CardTitle, SectionCard } from "./layout";

function containerTypeLabel(line: BookingContainerLineDetail): string {
  const t = line.containerType;
  if (t?.label) return t.label;
  if (t?.sizeFt) return `${t.sizeFt}ft${t.isReefer ? " Reefer" : ""} container`;
  return t?.code ?? "Container";
}

function Flag({ icon, label }: { icon: ReactNode; label: string }) {
  return (
    <Group
      component="span"
      gap={4}
      align="center"
      wrap="nowrap"
      style={{
        display: "inline-flex",
        borderRadius: 999,
        backgroundColor: "#F1F4F7",
        padding: "2px 8px",
        fontSize: 10.5,
        fontWeight: 700,
        color: "#475569",
      }}
    >
      {icon}
      {label}
    </Group>
  );
}

function UnitRow({ unit }: { unit: BookingContainerUnitDetail }) {
  return (
    <Table.Tr>
      <Table.Td>
        <Text fz={13} fw={700} c="#10202F">
          {unit.containerNumber}
        </Text>
      </Table.Td>
      <Table.Td>
        <Text fz={13} c="#475569">
          {unit.sealNumber || "—"}
        </Text>
      </Table.Td>
      <Table.Td>
        <Text fz={13} c="#475569">
          {Number(unit.vgmTons || 0) ? `${Number(unit.vgmTons).toLocaleString()} t` : "—"}
        </Text>
      </Table.Td>
      <Table.Td>
        <Group gap={4} wrap="wrap">
          {unit.isHazardous && (
            <Flag icon={<AlertTriangle size={11} />} label="Hazardous" />
          )}
          {unit.isReefer && <Flag icon={<Snowflake size={11} />} label="Reefer" />}
          {unit.isReturn && <Flag icon={<Undo2 size={11} />} label="Return" />}
          {!unit.isHazardous && !unit.isReefer && !unit.isReturn && (
            <Text fz={12} c="#9AA8B5">
              —
            </Text>
          )}
        </Group>
      </Table.Td>
      <Table.Td>
        <Text fz={12.5} fw={600} c={unit.receivedToPort ? "#0A6F4D" : "#9AA8B5"}>
          {unit.receivedToPort ? "Received" : "Pending"}
        </Text>
      </Table.Td>
    </Table.Tr>
  );
}

/**
 * Per-container breakdown for container bookings — real per-line data
 * (`bookingContainers`, joined with per-unit numbers/seals/VGM) rather than
 * the legacy `booking.containers` DTO shape, which the detail endpoint
 * never populates. Renders nothing for bulk bookings.
 */
export function ContainersCard({ booking }: { booking: BookingDetail }) {
  const lines = booking.bookingContainers ?? [];
  if (booking.freightType === "BULK" || lines.length === 0) return null;

  const totalUnits = lines.reduce((sum, c) => sum + Number(c.quantity || 0), 0);
  const totalVgm = totalVgmTons(booking);
  const allUnits = lines.flatMap((l) => l.units ?? []);

  return (
    <SectionCard>
      <Group justify="space-between" align="center" mb="md">
        <CardTitle>Containers</CardTitle>
        <Text fz="12.5px" fw={600} c="#9AA8B5">
          {totalUnits} unit{totalUnits !== 1 ? "s" : ""}
        </Text>
      </Group>

      <Table verticalSpacing="sm" horizontalSpacing={0} mb={allUnits.length ? "lg" : 0}>
        <Table.Thead>
          <Table.Tr>
            <Table.Th style={{ color: "#9AA8B5", fontSize: 11.5 }}>Type</Table.Th>
            <Table.Th style={{ color: "#9AA8B5", fontSize: 11.5 }}>Qty</Table.Th>
            <Table.Th style={{ color: "#9AA8B5", fontSize: 11.5 }}>VGM / unit</Table.Th>
            <Table.Th style={{ color: "#9AA8B5", fontSize: 11.5, textAlign: "right" }}>
              Total VGM
            </Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {lines.map((c, i) => {
            const lineVgm = Number(c.totalVgmTons || 0);
            return (
              <Table.Tr key={c.id ?? i}>
                <Table.Td>
                  <Group gap={8} wrap="wrap">
                    <Text fz={14} fw={700} c="#10202F">
                      {containerTypeLabel(c)}
                    </Text>
                    {c.isOverweight && (
                      <Flag icon={<AlertTriangle size={11} />} label="Overweight" />
                    )}
                    {!!c.hazardousQuantity && (
                      <Flag icon={<Flame size={11} />} label={`${c.hazardousQuantity} hazardous`} />
                    )}
                    {!!c.reeferQuantity && (
                      <Flag icon={<Snowflake size={11} />} label={`${c.reeferQuantity} reefer`} />
                    )}
                  </Group>
                </Table.Td>
                <Table.Td>
                  <Text fz={14} c="#10202F">
                    {c.quantity}
                  </Text>
                </Table.Td>
                <Table.Td>
                  <Text fz={14} c="#475569">
                    {fmtWeight(Number(c.vgmPerUnitTons || 0))}
                  </Text>
                </Table.Td>
                <Table.Td>
                  <Text fz={14} fw={700} c="#10202F" ta="right">
                    {fmtWeight(lineVgm)}
                  </Text>
                </Table.Td>
              </Table.Tr>
            );
          })}
        </Table.Tbody>
      </Table>

      {allUnits.length > 0 && (
        <Box>
          <Text fz="11.5px" fw={600} c="#9AA8B5" mb={8}>
            Container numbers
          </Text>
          <Table verticalSpacing="xs" horizontalSpacing={0}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th style={{ color: "#9AA8B5", fontSize: 11 }}>Container no.</Table.Th>
                <Table.Th style={{ color: "#9AA8B5", fontSize: 11 }}>Seal no.</Table.Th>
                <Table.Th style={{ color: "#9AA8B5", fontSize: 11 }}>VGM</Table.Th>
                <Table.Th style={{ color: "#9AA8B5", fontSize: 11 }}>Flags</Table.Th>
                <Table.Th style={{ color: "#9AA8B5", fontSize: 11 }}>Port status</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>
              {allUnits.map((u) => (
                <UnitRow key={u.id} unit={u} />
              ))}
            </Table.Tbody>
          </Table>
        </Box>
      )}

      <Box
        mt="sm"
        pt="sm"
        style={{ borderTop: "1px solid #F2F5F8", display: "flex", justifyContent: "space-between" }}
      >
        <Text fz={13} fw={600} c="#475569">
          Total weight (VGM)
        </Text>
        <Text fz={14} fw={800} c="#0A6F4D">
          {fmtWeight(totalVgm)}
        </Text>
      </Box>
    </SectionCard>
  );
}
