import { useMemo } from 'react';
import { ActionIcon, Badge, Button, Group, Text, Tooltip } from '@mantine/core';
import { ArrowRightLeft, ClipboardList, Coins, History } from 'lucide-react';
import { DataTable, type ColumnDef } from '@edr/ui-common';

import type { InventoryAction, WarehouseInventoryItem } from '@/types/warehouse';
import { INVENTORY_NEXT_ACTION } from '@/types/warehouse';
import { InventoryStatusBadge } from './badges';
import { formatDate, formatNumber, humanizeEnum } from './options';

interface WarehouseInventoryTableProps {
  items: WarehouseInventoryItem[];
  busyId?: string | null;
  onAdvance: (item: WarehouseInventoryItem, action: InventoryAction) => void;
  onMove: (item: WarehouseInventoryItem) => void;
  onHistory: (item: WarehouseInventoryItem) => void;
  onInspect?: (item: WarehouseInventoryItem) => void;
  onFeePreview?: (item: WarehouseInventoryItem) => void;
}

const itemKind = (item: WarehouseInventoryItem) => {
  if (item.containerId) return { label: 'Container', color: 'blue' };
  if (item.cargoId) return { label: 'Cargo', color: 'grape' };
  if (item.goodsId) return { label: 'Goods', color: 'orange' };
  return { label: '—', color: 'gray' };
};

const actionColor: Record<InventoryAction, string> = {
  store: 'blue',
  reserve: 'grape',
  'ready-for-loading': 'cyan',
  load: 'teal',
  dispatch: 'green',
};

export function WarehouseInventoryTable({
  items,
  busyId,
  onAdvance,
  onMove,
  onHistory,
  onInspect,
  onFeePreview,
}: WarehouseInventoryTableProps) {
  const columns = useMemo<ColumnDef<WarehouseInventoryItem>[]>(
    () => [
      {
        id: 'booking',
        header: 'Booking',
        cell: ({ row }) =>
          row.original.bookingId ? (
            <Tooltip label={row.original.bookingId} withArrow>
              <Text size="sm" fw={600}>
                {row.original.bookingId.slice(0, 8)}…
              </Text>
            </Tooltip>
          ) : (
            <Text size="sm" c="dimmed">
              —
            </Text>
          ),
      },
      {
        id: 'facility',
        header: 'Facility',
        cell: ({ row }) => row.original.warehouse?.facility?.name ?? '—',
      },
      { id: 'warehouse', header: 'Warehouse', cell: ({ row }) => row.original.warehouse?.code ?? '—' },
      { id: 'yard', header: 'Yard', cell: ({ row }) => row.original.yard?.code ?? '—' },
      { id: 'zone', header: 'Zone', cell: ({ row }) => row.original.zone?.code ?? '—' },
      {
        id: 'item',
        header: 'Item',
        cell: ({ row }) => {
          const kind = itemKind(row.original);
          return (
            <Badge color={kind.color} variant="light" size="sm" radius="md">
              {kind.label}
            </Badge>
          );
        },
      },
      { id: 'qty', header: 'Qty', cell: ({ row }) => formatNumber(row.original.quantity) },
      { id: 'weight', header: 'Weight', cell: ({ row }) => formatNumber(row.original.weight) },
      {
        id: 'status',
        header: 'Status',
        cell: ({ row }) => <InventoryStatusBadge status={row.original.status} />,
      },
      {
        id: 'arrived',
        header: 'Arrived',
        cell: ({ row }) => <Text size="xs">{formatDate(row.original.arrivedAt)}</Text>,
      },
      {
        id: 'actions',
        header: '',
        cell: ({ row }) => {
          const item = row.original;
          const busy = busyId === item.id;
          const nextAction = INVENTORY_NEXT_ACTION[item.status];
          return (
            <Group gap="xs" justify="flex-end" wrap="nowrap" onClick={(e) => e.stopPropagation()}>
              {nextAction && (
                <Button
                  size="compact-xs"
                  variant="light"
                  color={actionColor[nextAction]}
                  loading={busy}
                  onClick={() => onAdvance(item, nextAction)}
                >
                  {humanizeEnum(nextAction.replace(/-/g, '_'))}
                </Button>
              )}
              {item.status !== 'DISPATCHED' && (
                <Tooltip label="Move" withArrow>
                  <ActionIcon variant="subtle" color="gray" onClick={() => onMove(item)}>
                    <ArrowRightLeft size={16} />
                  </ActionIcon>
                </Tooltip>
              )}
              {onInspect && (
                <Tooltip label="Inspection / Report" withArrow>
                  <ActionIcon variant="subtle" color="orange" onClick={() => onInspect(item)}>
                    <ClipboardList size={16} />
                  </ActionIcon>
                </Tooltip>
              )}
              {onFeePreview && (
                <Tooltip label="Storage / Demurrage preview" withArrow>
                  <ActionIcon variant="subtle" color="teal" onClick={() => onFeePreview(item)}>
                    <Coins size={16} />
                  </ActionIcon>
                </Tooltip>
              )}
              <Tooltip label="History" withArrow>
                <ActionIcon variant="subtle" color="gray" onClick={() => onHistory(item)}>
                  <History size={16} />
                </ActionIcon>
              </Tooltip>
            </Group>
          );
        },
      },
    ],
    [busyId, onAdvance, onMove, onHistory, onInspect, onFeePreview],
  );

  return (
    <DataTable
      columns={columns}
      data={items}
      status="success"
      emptyMessage="No inventory items found."
      containerClassName="border-0 shadow-none"
    />
  );
}
