import { useMemo } from 'react';
import { ActionIcon, Group, Text } from '@mantine/core';
import { Eye, Pencil } from 'lucide-react';
import { DataTable, type ColumnDef } from '@edr/ui-common';

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

import { api } from '@/services/api';
import type { Warehouse } from '@/types/warehouse';
import { WarehouseStatusBadge, WarehouseTypeBadge } from './badges';
import { formatCapacity } from './options';

interface WarehouseTableProps {
  warehouses: Warehouse[];
  onView: (warehouse: Warehouse) => void;
  onEdit: (warehouse: Warehouse) => void;
}

export function WarehouseTable({ warehouses, onView, onEdit }: WarehouseTableProps) {
  const { data: stations } = useQuery(
    api.stations.list.queryOptions({ staleTime: 5 * 60 * 1000 }),
  );
  const stationNameById = useMemo(
    () => new Map((stations ?? []).map((s) => [s.id, s.name])),
    [stations],
  );

  const columns: ColumnDef<Warehouse>[] = [
    {
      id: 'code',
      header: 'Code',
      cell: ({ row }) => (
        <Text
          fw={600}
          size="sm"
          c="edr-green.7"
          style={{ cursor: 'pointer' }}
          onClick={() => onView(row.original)}
        >
          {row.original.code}
        </Text>
      ),
    },
    { id: 'name', header: 'Name', cell: ({ row }) => row.original.name },
    {
      id: 'facility',
      header: 'Facility',
      cell: ({ row }) => {
        const name = row.original.stationId
          ? stationNameById.get(row.original.stationId)
          : undefined;
        return name ? (
          <Text size="sm" fw={500}>
            {name}
          </Text>
        ) : (
          <Text size="sm" c="dimmed">
            —
          </Text>
        );
      },
    },
    {
      id: 'type',
      header: 'Type',
      cell: ({ row }) => <WarehouseTypeBadge type={row.original.type} />,
    },
    {
      id: 'location',
      header: 'Location',
      cell: ({ row }) => row.original.locationName ?? '—',
    },
    {
      id: 'weight',
      header: 'Weight (cur / cap)',
      cell: ({ row }) => formatCapacity(row.original.currentWeight, row.original.capacityWeight),
    },
    {
      id: 'containers',
      header: 'Containers (cur / cap)',
      cell: ({ row }) =>
        formatCapacity(row.original.currentContainers, row.original.capacityContainers),
    },
    {
      id: 'status',
      header: 'Status',
      cell: ({ row }) => <WarehouseStatusBadge status={row.original.status} />,
    },
    {
      id: 'actions',
      header: '',
      cell: ({ row }) => (
        <Group gap="xs" justify="flex-end" wrap="nowrap" onClick={(e) => e.stopPropagation()}>
          <ActionIcon variant="subtle" color="gray" onClick={() => onView(row.original)} title="View">
            <Eye size={16} />
          </ActionIcon>
          <ActionIcon variant="subtle" color="gray" onClick={() => onEdit(row.original)} title="Edit">
            <Pencil size={16} />
          </ActionIcon>
        </Group>
      ),
    },
  ];

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