import { Link, useParams } from "react-router-dom";
import { isAxiosError } from "axios";
import {
  ArrowLeft,
  CalendarClock,
  CheckCircle2,
  Flag,
  MapPin,
  Navigation,
  Train,
} from "lucide-react";
import {
  Badge,
  Box,
  Button,
  Group,
  Loader,
  Paper,
  Progress,
  Stack,
  Text,
  ThemeIcon,
  Timeline,
  Title,
} from "@mantine/core";

import { PageContainer } from "@/components/page";
import { RouteCorridorTrack } from "@/components/trainScheduling/RouteCorridorTrack";
import { RouteCorridor, StatusPill } from "@/components/trainScheduling/scheduleVisuals";
import { freightBrand } from "@/theme/freight-brand";
import { useMutation, useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { useToast } from "@/hooks/use-toast";

const parseError = (error: unknown, fallback: string) => {
  if (isAxiosError(error)) {
    const data = error.response?.data as Record<string, unknown> | undefined;
    const message = data?.message;
    if (Array.isArray(message)) return message.join(", ");
    if (typeof message === "string") return message;
  }
  return fallback;
};

function formatDateTime(iso?: string | null) {
  if (!iso) return "—";
  return new Date(iso).toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

/** Compact icon + label + value cell used in the header meta strip. */
function MetaStat({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  return (
    <Group gap={8} wrap="nowrap" style={{ minWidth: 0 }}>
      <ThemeIcon size={32} radius="md" variant="light" color="edr-green">
        {icon}
      </ThemeIcon>
      <Stack gap={0} style={{ minWidth: 0 }}>
        <Text size="10px" fw={700} tt="uppercase" c="dimmed" style={{ letterSpacing: 0.5 }}>
          {label}
        </Text>
        <Text size="sm" fw={700} c="dark.5" truncate>
          {value}
        </Text>
      </Stack>
    </Group>
  );
}

export default function TrainScheduleTrackPage() {
  const { scheduleId } = useParams<{ scheduleId: string }>();
  const { toast } = useToast();
  const trackQuery = useQuery(
    api.trainScheduling.trainTrack.queryOptions({
      input: { id: scheduleId ?? "" },
      enabled: Boolean(scheduleId),
    }),
  );
  const recordCheckpoint = useMutation(
    api.trainScheduling.recordCheckpoint.mutationOptions(),
  );

  if (trackQuery.isLoading) {
    return (
      <PageContainer>
        <Group justify="center" py="xl">
          <Loader size="sm" color="edr-green" />
        </Group>
      </PageContainer>
    );
  }

  const track = trackQuery.data;
  if (!track || !scheduleId) {
    return (
      <PageContainer>
        <Text c="dimmed" py="xl">
          Tracking data not found.
        </Text>
      </PageContainer>
    );
  }

  const canLog = track.status === "DISPATCHED";
  const totalStations = track.stations.length;
  const reached = Math.min(track.currentSequenceNo + 1, totalStations);
  const progressPct = totalStations > 1 ? (track.currentSequenceNo / (totalStations - 1)) * 100 : 0;
  const clampedPct = Math.min(100, Math.max(0, progressPct));
  const currentStation = track.stations[Math.max(0, track.currentSequenceNo)]?.label ?? "—";

  const handleLog = (sequenceNo: number) => {
    const isFinal = sequenceNo === track.stations[totalStations - 1]?.sequenceNo;
    recordCheckpoint.mutate(
      { id: scheduleId, payload: { sequenceNo } },
      {
        onSuccess: () => {
          toast({
            title: isFinal
              ? "Train arrived — assets freed, moved to destination yard"
              : "Checkpoint logged",
          });
        },
        onError: (err) =>
          toast({
            title: "Could not log checkpoint",
            description: parseError(err, "Please try again"),
            variant: "destructive",
          }),
      },
    );
  };

  return (
    <PageContainer>
      <Button
        component={Link}
        to={`/dashboard/operations/train-scheduling-v2/${scheduleId}`}
        variant="subtle"
        color="gray"
        size="compact-sm"
        leftSection={<ArrowLeft size={16} />}
        w="fit-content"
      >
        Back to schedule
      </Button>

      {/* Header */}
      <Paper radius="lg" withBorder p="lg">
        <Stack gap="lg">
          <Group justify="space-between" align="flex-start" wrap="wrap" gap="md">
            <Group gap="md" align="flex-start" wrap="nowrap" style={{ minWidth: 0 }}>
              <Box
                style={{
                  width: 48,
                  height: 48,
                  borderRadius: 12,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  background: freightBrand.gradient,
                  color: "white",
                  flexShrink: 0,
                }}
              >
                <Navigation size={24} />
              </Box>
              <Stack gap={6} style={{ minWidth: 0 }}>
                <Group gap="sm" align="center" wrap="wrap">
                  <Title order={3} fw={800}>
                    Train tracking
                  </Title>
                  {track.trainNumber ? (
                    <Badge variant="light" color="edr-green" radius="sm">
                      {track.trainNumber}
                    </Badge>
                  ) : null}
                  {track.direction ? (
                    <Badge variant="light" color="gray" radius="sm">
                      {track.direction}
                    </Badge>
                  ) : null}
                </Group>
                <Box maw={360}>
                  <RouteCorridor origin={track.origin} destination={track.destination} variant="compact" />
                </Box>
              </Stack>
            </Group>
            <StatusPill status={track.status} />
          </Group>

          {/* Journey progress */}
          <Box>
            <Group justify="space-between" mb={6}>
              <Text size="xs" fw={700} c="gray.7" tt="uppercase" style={{ letterSpacing: 0.4 }}>
                Journey progress
              </Text>
              <Text size="xs" fw={700} c="edr-green.8">
                {reached} / {totalStations} stations · {Math.round(clampedPct)}%
              </Text>
            </Group>
            <Progress
              value={clampedPct}
              size="lg"
              radius="xl"
              color="edr-green"
              striped={track.status === "DISPATCHED"}
              animated={track.status === "DISPATCHED"}
            />
          </Box>

          {/* Meta strip */}
          <Group justify="space-between" wrap="wrap" gap="lg">
            <MetaStat icon={<MapPin size={16} />} label="Current" value={currentStation} />
            <MetaStat
              icon={<CalendarClock size={16} />}
              label="Departed"
              value={formatDateTime(track.actualDepartureAt)}
            />
            <MetaStat
              icon={<Flag size={16} />}
              label="Arrived"
              value={formatDateTime(track.actualArrivalAt)}
            />
            <MetaStat
              icon={<Train size={16} />}
              label="Stations"
              value={`${reached} of ${totalStations}`}
            />
          </Group>
        </Stack>
      </Paper>

      {/* Corridor */}
      <Paper radius="lg" p="lg" withBorder>
        <Stack gap="md">
          <Group gap="sm" align="center" wrap="nowrap">
            <ThemeIcon size={34} radius="md" variant="light" color="edr-green">
              <Navigation size={17} />
            </ThemeIcon>
            <Stack gap={0}>
              <Text fw={800} size="sm">
                Route corridor
              </Text>
              <Text size="xs" c="dimmed">
                {canLog
                  ? "Log the train passing each station; the final station marks arrival."
                  : track.status === "ARRIVED"
                    ? "This train has arrived at its destination."
                    : "Tracking becomes available once the train is dispatched."}
              </Text>
            </Stack>
          </Group>

          <RouteCorridorTrack
            stations={track.stations}
            currentSequenceNo={track.currentSequenceNo}
            checkpoints={track.checkpoints}
            canLog={canLog}
            loggingSeq={
              recordCheckpoint.isPending ? recordCheckpoint.variables?.payload.sequenceNo : null
            }
            onLogCheckpoint={handleLog}
          />
        </Stack>
      </Paper>

      {/* Checkpoint log */}
      <Paper radius="lg" p="lg" withBorder>
        <Group gap="sm" align="center" wrap="nowrap" mb="md">
          <ThemeIcon size={34} radius="md" variant="light" color="edr-green">
            <CheckCircle2 size={17} />
          </ThemeIcon>
          <Stack gap={0}>
            <Text fw={800} size="sm">
              Checkpoint log
            </Text>
            <Text size="xs" c="dimmed">
              {track.checkpoints.length} event{track.checkpoints.length === 1 ? "" : "s"} recorded
            </Text>
          </Stack>
        </Group>

        {track.checkpoints.length === 0 ? (
          <Stack align="center" gap="xs" py="xl">
            <ThemeIcon size={44} radius="xl" variant="light" color="gray">
              <MapPin size={20} />
            </ThemeIcon>
            <Text size="sm" fw={600} c="gray.7">
              No checkpoints yet
            </Text>
            <Text size="xs" c="dimmed" ta="center" maw={300}>
              Each station the train passes will be logged here with its timestamp.
            </Text>
          </Stack>
        ) : (
          <Timeline active={track.checkpoints.length} bulletSize={22} lineWidth={2} color="edr-green">
            {track.checkpoints.map((cp) => (
              <Timeline.Item
                key={cp.id}
                bullet={cp.kind === "ARRIVED" ? <CheckCircle2 size={13} /> : <MapPin size={12} />}
                title={
                  <Group gap="sm">
                    <Text fw={700} size="sm">
                      {cp.label ?? `Station ${cp.sequenceNo}`}
                    </Text>
                    <Badge
                      size="xs"
                      radius="sm"
                      variant="light"
                      color={cp.kind === "ARRIVED" ? "teal" : cp.kind === "DEPARTED" ? "blue" : "edr-green"}
                    >
                      {cp.kind}
                    </Badge>
                  </Group>
                }
              >
                <Text size="xs" c="dimmed">
                  {formatDateTime(cp.occurredAt)}
                </Text>
                {cp.note ? (
                  <Text size="xs" mt={2}>
                    {cp.note}
                  </Text>
                ) : null}
              </Timeline.Item>
            ))}
          </Timeline>
        )}
      </Paper>
    </PageContainer>
  );
}
