import { Fragment } from "react";
import { Badge, Box, Button, Group, Stack, Text } from "@mantine/core";
import { Check, Flag, MapPin, Train } from "lucide-react";

import { freightBrand } from "@/theme/freight-brand";
import type { TrainCheckpoint, TrackStation } from "@/types/trainScheduling";

export interface RouteCorridorTrackProps {
  stations: TrackStation[];
  /** Highest sequenceNo reached so far (−1 = not yet departed). */
  currentSequenceNo: number;
  checkpoints: TrainCheckpoint[];
  /** True when the train is DISPATCHED and staff may log progress. */
  canLog: boolean;
  loggingSeq?: number | null;
  onLogCheckpoint?: (sequenceNo: number) => void;
}

const COLUMN_WIDTH = 150;
const PASSED = freightBrand.primary;
const UPCOMING = "var(--mantine-color-gray-3)";

function railColor(active: boolean) {
  return active ? PASSED : UPCOMING;
}

export function RouteCorridorTrack({
  stations,
  currentSequenceNo,
  checkpoints,
  canLog,
  loggingSeq,
  onLogCheckpoint,
}: RouteCorridorTrackProps) {
  const bySeq = new Map(checkpoints.map((c) => [c.sequenceNo, c]));
  const lastIndex = stations.length - 1;

  return (
    <Box style={{ overflowX: "auto", paddingBottom: 4 }}>
      <Group
        gap={0}
        wrap="nowrap"
        align="flex-start"
        style={{ minWidth: stations.length * COLUMN_WIDTH }}
      >
        {stations.map((station, index) => {
          const passed = station.sequenceNo <= currentSequenceNo;
          const isCurrent = station.sequenceNo === currentSequenceNo;
          const isFinal = index === lastIndex;
          const isNext = canLog && station.sequenceNo === currentSequenceNo + 1;
          const checkpoint = bySeq.get(station.sequenceNo);
          // left rail solid once this node is reached; right rail solid once the next node is reached
          const leftActive = station.sequenceNo <= currentSequenceNo;
          const rightActive = station.sequenceNo + 1 <= currentSequenceNo;

          return (
            <Fragment key={station.sequenceNo}>
              <Stack gap={6} align="center" style={{ width: COLUMN_WIDTH, flexShrink: 0 }}>
                {/* rail + node */}
                <Box style={{ position: "relative", height: 44, width: "100%" }}>
                  {index > 0 && (
                    <Box
                      style={{
                        position: "absolute",
                        top: 21,
                        left: 0,
                        width: "50%",
                        height: 3,
                        borderRadius: 2,
                        background: railColor(leftActive),
                      }}
                    />
                  )}
                  {index < lastIndex && (
                    <Box
                      style={{
                        position: "absolute",
                        top: 21,
                        left: "50%",
                        width: "50%",
                        height: 3,
                        borderRadius: 2,
                        background: railColor(rightActive),
                      }}
                    />
                  )}

                  {/* train marker hovering over the current node */}
                  {isCurrent && (
                    <Box
                      style={{
                        position: "absolute",
                        top: -8,
                        left: "50%",
                        transform: "translateX(-50%)",
                        color: freightBrand.primaryDark,
                      }}
                    >
                      <Train size={18} />
                    </Box>
                  )}

                  {/* node */}
                  <Box
                    style={{
                      position: "absolute",
                      top: 12,
                      left: "50%",
                      transform: "translateX(-50%)",
                      width: 22,
                      height: 22,
                      borderRadius: "50%",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      background: passed ? PASSED : "white",
                      border: `2px solid ${
                        passed
                          ? PASSED
                          : isNext
                            ? freightBrand.primaryLight
                            : "var(--mantine-color-gray-4)"
                      }`,
                      boxShadow: isCurrent ? `0 0 0 4px ${freightBrand.ring}` : "none",
                      color: "white",
                      zIndex: 1,
                    }}
                  >
                    {passed ? (
                      <Check size={13} />
                    ) : isFinal ? (
                      <Flag size={12} color="var(--mantine-color-gray-5)" />
                    ) : (
                      <MapPin size={12} color="var(--mantine-color-gray-5)" />
                    )}
                  </Box>
                </Box>

                {/* label */}
                <Stack gap={0} align="center" style={{ minWidth: 0, padding: "0 6px" }}>
                  <Text
                    size="xs"
                    fw={passed ? 700 : 600}
                    ta="center"
                    lineClamp={2}
                    c={passed ? "edr-green.8" : "dimmed"}
                  >
                    {station.label}
                  </Text>
                  {index === 0 ? (
                    <Badge size="xs" variant="light" color="gray" radius="sm">
                      Origin
                    </Badge>
                  ) : isFinal ? (
                    <Badge size="xs" variant="light" color="gray" radius="sm">
                      Destination
                    </Badge>
                  ) : null}
                </Stack>

                {/* checkpoint time or action */}
                {checkpoint ? (
                  <Text size="10px" c="dimmed" ta="center">
                    {new Date(checkpoint.occurredAt).toLocaleString(undefined, {
                      month: "short",
                      day: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </Text>
                ) : isNext ? (
                  <Button
                    size="compact-xs"
                    radius="md"
                    color={isFinal ? "teal" : "edr-green"}
                    variant={isFinal ? "filled" : "light"}
                    loading={loggingSeq === station.sequenceNo}
                    onClick={() => onLogCheckpoint?.(station.sequenceNo)}
                  >
                    {isFinal ? "Mark arrived" : "Log pass"}
                  </Button>
                ) : (
                  <Box style={{ height: 22 }} />
                )}
              </Stack>
            </Fragment>
          );
        })}
      </Group>
    </Box>
  );
}
