import { Center, Loader, Table, Text } from '@mantine/core';

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

import { api } from '@/services/api';
import { formatDate } from './options';

const shortId = (id?: string | null) => (id ? `${id.slice(0, 8)}…` : '—');

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

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

  if (movements.length === 0) {
    return (
      <Text c="dimmed" ta="center" py="md" size="sm">
        No movements recorded for this item.
      </Text>
    );
  }

  return (
    <Table.ScrollContainer minWidth={640}>
      <Table verticalSpacing="xs" striped>
        <Table.Thead>
          <Table.Tr>
            <Table.Th>From (W / Y / Z)</Table.Th>
            <Table.Th>To (W / Y / Z)</Table.Th>
            <Table.Th>Remarks</Table.Th>
            <Table.Th>By</Table.Th>
            <Table.Th>When</Table.Th>
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {movements.map((m) => (
            <Table.Tr key={m.id}>
              <Table.Td>
                <Text size="xs">
                  {shortId(m.fromWarehouseId)} / {shortId(m.fromYardId)} / {shortId(m.fromZoneId)}
                </Text>
              </Table.Td>
              <Table.Td>
                <Text size="xs">
                  {shortId(m.toWarehouseId)} / {shortId(m.toYardId)} / {shortId(m.toZoneId)}
                </Text>
              </Table.Td>
              <Table.Td>{m.remarks ?? '—'}</Table.Td>
              <Table.Td>{m.movedBy ?? '—'}</Table.Td>
              <Table.Td>
                <Text size="xs">{formatDate(m.movedAt)}</Text>
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
    </Table.ScrollContainer>
  );
}
