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

import type { InventoryInquiryResult } from '@/types/warehouse';
import { InventoryStatusBadge } from './badges';
import { formatDate, formatNumber } from './options';

interface WarehouseInquiryTableProps {
  results: InventoryInquiryResult[];
}

const itemDescriptor = (result: InventoryInquiryResult) => {
  if (result.containerNumber) return `Container ${result.containerNumber}`;
  if (result.cargoType) return `Cargo · ${result.cargoType}`;
  if (result.cargoDescription) return `Cargo · ${result.cargoDescription}`;
  if (result.goodsId) return 'Goods';
  return '—';
};

const columns: ColumnDef<InventoryInquiryResult>[] = [
  {
    id: 'booking',
    header: 'Booking',
    cell: ({ row }) => (
      <Text size="sm" fw={600}>
        {row.original.bookingNumber ?? row.original.bookingId.slice(0, 8)}
      </Text>
    ),
  },
  { id: 'customer', header: 'Customer', cell: ({ row }) => row.original.customerName ?? '—' },
  { id: 'item', header: 'Item', cell: ({ row }) => itemDescriptor(row.original) },
  {
    id: 'warehouse',
    header: 'Warehouse',
    cell: ({ row }) => (
      <Stack gap={0}>
        <Text size="sm">{row.original.warehouse?.name ?? '—'}</Text>
        {row.original.warehouse?.code && (
          <Text size="xs" c="dimmed">
            {row.original.warehouse.code}
          </Text>
        )}
      </Stack>
    ),
  },
  { id: 'yard', header: 'Yard', cell: ({ row }) => row.original.yard?.name ?? '—' },
  { id: 'zone', header: 'Zone', cell: ({ row }) => row.original.zone?.name ?? '—' },
  {
    id: 'status',
    header: 'Status',
    cell: ({ row }) => <InventoryStatusBadge status={row.original.status} />,
  },
  { id: 'qty', header: 'Qty', cell: ({ row }) => formatNumber(row.original.quantity) },
  { id: 'weight', header: 'Weight', cell: ({ row }) => formatNumber(row.original.weight) },
  {
    id: 'arrived',
    header: 'Arrived',
    cell: ({ row }) => <Text size="xs">{formatDate(row.original.arrivedAt)}</Text>,
  },
  {
    id: 'ready',
    header: 'Ready',
    cell: ({ row }) => <Text size="xs">{formatDate(row.original.readyForLoadingAt)}</Text>,
  },
];

export function WarehouseInquiryTable({ results }: WarehouseInquiryTableProps) {
  return (
    <DataTable
      columns={columns}
      data={results}
      status="success"
      emptyMessage="No matching items. Adjust your search to locate cargo, containers or goods."
      containerClassName="border-0 shadow-none"
    />
  );
}
