import { Box, Card, Group, Stack, Text, ThemeIcon } from "@mantine/core";
import { History, PackageX } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";

interface RemovalLogPanelProps {
  scheduleId: string;
}

export const RemovalLogPanel = ({ scheduleId }: RemovalLogPanelProps) => {
  const removalQuery = useQuery(
    api.trainScheduling.compositionRemovals.queryOptions({
      input: { scheduleId },
      enabled: Boolean(scheduleId),
    }),
  );

  if (removalQuery.isLoading) {
    return (
      <Text size="sm" c="dimmed">
        Loading...
      </Text>
    );
  }

  const removals = removalQuery.data ?? [];

  if (removals.length === 0) {
    return (
      <Stack align="center" gap="xs" py="xl">
        <ThemeIcon size={44} radius="xl" variant="light" color="gray">
          <History size={20} />
        </ThemeIcon>
        <Text size="sm" fw={600} c="gray.7">
          No removals yet
        </Text>
        <Text size="xs" c="dimmed" ta="center" maw={220}>
          Bookings removed from this train will appear here for audit.
        </Text>
      </Stack>
    );
  }

  return (
    <Stack gap="xs">
      {removals.map((removal) => (
        <Card key={removal.id} padding="xs" radius="md" withBorder>
          <Group gap={8} wrap="nowrap" align="flex-start">
            <ThemeIcon size={30} radius="md" variant="light" color="red">
              <PackageX size={16} />
            </ThemeIcon>
            <Box style={{ flex: 1, minWidth: 0 }}>
              <Text size="sm" fw={700} truncate>
                {removal.bookingReference || "Unknown booking"}
              </Text>
              <Text size="11px" c="dimmed">
                Removed{" "}
                {new Date(removal.removedAt).toLocaleString("en-GB", {
                  timeZone: "Africa/Addis_Ababa",
                  day: "2-digit",
                  month: "short",
                  hour: "2-digit",
                  minute: "2-digit",
                  hour12: false,
                })}{" "}
                EAT
              </Text>
              {removal.notes ? (
                <Text size="11px" c="dimmed" mt={2} lineClamp={2}>
                  {removal.notes}
                </Text>
              ) : null}
            </Box>
          </Group>
        </Card>
      ))}
    </Stack>
  );
};
