import { Center, Loader, Text, Timeline } from '@mantine/core';
import {
  ArrowRightLeft,
  ClipboardCheck,
  PackageCheck,
  PackagePlus,
  Send,
  Truck,
  Warehouse,
} from 'lucide-react';

import { useQuery } from '@tanstack/react-query';

import { api } from '@/services/api';
import type { ActivityType } from '@/types/warehouse';
import { formatDate, humanizeEnum } from './options';

const activityIcon: Record<ActivityType, React.ReactNode> = {
  INVENTORY_RECEIVED: <PackagePlus size={14} />,
  INVENTORY_STORED: <Warehouse size={14} />,
  INVENTORY_MOVED: <ArrowRightLeft size={14} />,
  INVENTORY_RESERVED: <ClipboardCheck size={14} />,
  READY_FOR_LOADING: <PackageCheck size={14} />,
  INVENTORY_LOADED: <Truck size={14} />,
  INVENTORY_DISPATCHED: <Send size={14} />,
};

export function ActivityTimeline({ inventoryId }: { inventoryId: string }) {
  const { data, isLoading } = useQuery(
    api.warehouses.activity.queryOptions({
      input: { id: inventoryId },
      enabled: Boolean(inventoryId),
    }),
  );
  const items = data ?? [];

  if (isLoading) {
    return (
      <Center py="lg">
        <Loader size="sm" />
      </Center>
    );
  }

  if (items.length === 0) {
    return (
      <Text c="dimmed" ta="center" py="md" size="sm">
        No activity recorded yet.
      </Text>
    );
  }

  return (
    <Timeline active={items.length} bulletSize={24} lineWidth={2}>
      {items.map((log) => (
        <Timeline.Item key={log.id} bullet={activityIcon[log.activityType]} title={humanizeEnum(log.activityType)}>
          {log.description && (
            <Text size="sm" c="dimmed">
              {log.description}
            </Text>
          )}
          <Text size="xs" mt={4} c="dimmed">
            {log.performedBy ?? 'system'} · {formatDate(log.createdAt)}
          </Text>
        </Timeline.Item>
      ))}
    </Timeline>
  );
}
