import { useGetItemsQuery, useDeleteItemMutation, type Item } from '../../api/item-api';
import { AdvancedTable, notify, useErrorHandler, useServerTable } from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';
import { itemColumns } from './columns';
import { itemActionsColumn } from './actions';

export function ItemTable() {
  const { data, isLoading, refetch } = useGetItemsQuery({});
  const [deleteItem] = useDeleteItemMutation();
  const { handleError } = useErrorHandler();
  const showDate = useDateDisplayer();
  const table = useServerTable();

  const handleDelete = async (item: Item) => {
    try {
      await deleteItem(item.id).unwrap();
      notify.success('Item deleted');
    } catch (e) {
      handleError(e);
    }
  };

  const paged = table.paginate(data?.data ?? []);

  return (
    <AdvancedTable<Item>
      tableName="Items"
      columns={[...itemColumns(showDate), itemActionsColumn({ onDelete: handleDelete })]}
      data={paged.rows}
      itemCount={paged.itemCount}
      pageIndex={paged.pageIndex}
      onPageChange={table.setPageIndex}
      pageSize={table.pageSize}
      isLoading={isLoading}
      refresh={refetch}
      emptyText="No items found"
    />
  );
}
