import { Badge, Box, Button, Card, Group, Progress, Stack, Text, ThemeIcon } from "@mantine/core";
import {
  Building2,
  Container as ContainerIcon,
  Fuel,
  Package,
  TrainFront,
  Trash2,
  X,
} from "lucide-react";
import type { TrainScheduleDetail } from "@/types/trainScheduling";
import { ContainerNumberInput } from "./ContainerNumberInput";
import { freightBrand } from "@/theme/freight-brand";

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

interface WagonCardProps {
  wagon: Wagon;
  company?: string | null;
  scheduleId: string;
  scheduleStatus?: string;
  onRemoveBooking: (wagon: Wagon) => void;
  onRemoveWagon: (wagonId: string) => void;
}

export const WagonCard = ({
  wagon,
  company,
  scheduleId,
  scheduleStatus,
  onRemoveBooking,
  onRemoveWagon,
}: WagonCardProps) => {
  const isDispatched = scheduleStatus === "DISPATCHED";
  const allocation = wagon.allocations?.[0];
  const hasAllocations = Boolean(allocation);
  const isBulk = (allocation?.loadType ?? "").toUpperCase().includes("BULK");

  const weightUsed = allocation?.allocatedWeightTons ?? 0;
  const weightMax = wagon.capacityTons ?? 0;
  const weightPercent = weightMax ? (weightUsed / weightMax) * 100 : 0;

  const wagonType = wagon.wagonType?.code || "UNKNOWN";

  return (
    <Card padding="sm" radius="md" withBorder style={{ borderColor: freightBrand.mutedBorder }}>
      <Card.Section withBorder inheritPadding py="xs" style={{ background: freightBrand.mutedBg }}>
        <Group justify="space-between">
          <Group gap={6}>
            <ThemeIcon size={28} radius="md" variant="white" color="edr-green">
              <TrainFront size={16} />
            </ThemeIcon>
            <div>
              <Group gap={4}>
                <Text size="sm" fw={800}>
                  Wagon #{wagon.sequenceNo}
                </Text>
                <Badge size="xs" variant="light" color="edr-green">
                  {wagonType}
                </Badge>
              </Group>
              {wagon.physicalWagonNumber || wagon.physicalWagonId ? (
                <Text size="10px" c="dimmed">
                  {wagon.physicalWagonNumber || wagon.physicalWagonId?.slice(0, 8)}
                </Text>
              ) : null}
            </div>
          </Group>
          {hasAllocations ? (
            <Badge
              size="sm"
              variant="light"
              color={isBulk ? "orange" : "cyan"}
              leftSection={isBulk ? <Fuel size={11} /> : <ContainerIcon size={11} />}
            >
              {isBulk ? "Bulk" : "Container"}
            </Badge>
          ) : null}
        </Group>
      </Card.Section>

      <Stack gap="sm" mt="sm">
        {hasAllocations && allocation ? (
          <>
            {company ? (
              <Group gap={6} wrap="nowrap">
                <Building2 size={14} color={freightBrand.primary} />
                <Text size="sm" fw={700} truncate>
                  {company}
                </Text>
              </Group>
            ) : null}

            <Group gap={6} wrap="nowrap">
              <Package size={14} color="var(--mantine-color-gray-6)" />
              <Text size="sm" c="dimmed">
                {allocation.bookingReference || "Unknown booking"}
              </Text>
            </Group>

            {allocation.loadType === "CONTAINER" && allocation.containerItems?.length ? (
              <Box>
                <Text size="10px" c="dimmed" fw={700} tt="uppercase" mb={4}>
                  Containers
                </Text>
                <Stack gap={6}>
                  {allocation.containerItems.map((item, idx) => (
                    <Group key={item.id} gap={8} wrap="nowrap">
                      <ContainerIcon size={13} color="var(--mantine-color-cyan-7)" />
                      <Text size="xs" c="dimmed">
                        #{idx + 1}
                      </Text>
                      <ContainerNumberInput
                        value={item.containerNumber ?? null}
                        itemId={item.id}
                        scheduleId={scheduleId}
                        disabled={isDispatched}
                      />
                    </Group>
                  ))}
                </Stack>
              </Box>
            ) : null}

            {isBulk ? (
              <Group gap={6} wrap="nowrap">
                <Fuel size={14} color="var(--mantine-color-orange-6)" />
                <Text size="xs" c="dimmed">
                  {allocation.bulkLoad?.cargoDescription || "Bulk load"}
                </Text>
              </Group>
            ) : null}

            <Box>
              <Group justify="space-between" mb={4}>
                <Text size="xs" c="dimmed" fw={600}>
                  Weight
                </Text>
                <Text size="xs" c="dimmed">
                  {weightUsed.toFixed(1)} / {weightMax.toFixed(1)} T
                </Text>
              </Group>
              <Progress
                value={Math.min(weightPercent, 100)}
                color={weightPercent > 90 ? "red" : weightPercent > 75 ? "orange" : "edr-green"}
                size="sm"
                radius="xl"
              />
            </Box>

            {!isDispatched ? (
              <Button
                variant="light"
                color="red"
                size="xs"
                leftSection={<X size={14} />}
                onClick={() => onRemoveBooking(wagon)}
                fullWidth
              >
                Remove booking
              </Button>
            ) : null}
          </>
        ) : (
          <Stack gap="xs" align="center" py="sm">
            <ThemeIcon size={36} radius="xl" variant="light" color="gray">
              <TrainFront size={18} />
            </ThemeIcon>
            <Text size="sm" c="dimmed">
              Empty slot
            </Text>
            {!isDispatched ? (
              <Button
                variant="subtle"
                color="gray"
                size="xs"
                leftSection={<Trash2 size={14} />}
                onClick={() => onRemoveWagon(wagon.id)}
              >
                Remove wagon
              </Button>
            ) : null}
          </Stack>
        )}
      </Stack>
    </Card>
  );
};
