import { Badge, Card, Group, Text } from '@mantine/core';
import { DataTable, type ColumnDef } from '@edr/ui-common';

import { PageContainer, PageHeader } from '@/components/page';
import { useQuery } from '@tanstack/react-query';

import { FreightVisual, VisualEmptyState, formatDate, formatNumber } from '@/components/warehouses';
import { api } from '@/services/api';
import type { WarehouseLoading } from '@/types/warehouse';

type Loading = WarehouseLoading;

const columns: ColumnDef<Loading>[] = [
  {
    id: 'wagon',
    header: 'Wagon',
    cell: ({ row }) => (
      <Group gap={6} wrap="nowrap">
        <FreightVisual variant="wagon" size={22} />
        <Text fw={600} size="sm">
          {row.original.wagonNumber ?? row.original.wagonId.slice(0, 8)}
        </Text>
      </Group>
    ),
  },
  {
    id: 'warehouse',
    header: 'Warehouse',
    cell: ({ row }) =>
      row.original.inventory?.warehouse
        ? `${row.original.inventory.warehouse.name} (${row.original.inventory.warehouse.code})`
        : '—',
  },
  {
    id: 'zone',
    header: 'Zone',
    cell: ({ row }) => (row.original.inventory?.zone ? row.original.inventory.zone.name : '—'),
  },
  {
    id: 'weight',
    header: 'Loaded Weight (kg)',
    cell: ({ row }) => formatNumber(row.original.loadedWeight),
  },
  {
    id: 'loadedAt',
    header: 'Loaded At',
    cell: ({ row }) => formatDate(row.original.loadedAt),
  },
  {
    id: 'status',
    header: 'Status',
    cell: ({ row }) => (
      <Badge
        variant="light"
        color={row.original.inventory?.status === 'DISPATCHED' ? 'edr-green' : 'teal'}
        size="sm"
      >
        {row.original.inventory?.status ?? 'LOADED'}
      </Badge>
    ),
  },
];

/** Record of every inventory item loaded onto a wagon. */
export default function LoadedInventoryPage() {
  const { data, isLoading } = useQuery(
    api.warehouses.loadings.queryOptions({ input: {} }),
  );
  const loadings = data ?? [];

  return (
    <PageContainer>
      <PageHeader
        title="Loaded Inventory"
        subtitle="Items loaded onto wagons, with their loading records."
      />

      <Card>
        {!isLoading && loadings.length === 0 ? (
          <VisualEmptyState
            variant="container"
            title="No loaded inventory yet"
            description="Once items are loaded onto a wagon, their records show here."
          />
        ) : (
          <DataTable
            columns={columns}
            data={loadings}
            status={isLoading ? 'loading' : 'success'}
            containerClassName="border-0 shadow-none"
          />
        )}
      </Card>
    </PageContainer>
  );
}
