import React, { ReactElement, useCallback } from 'react';
import { RenderItem } from './RenderItem';
import { SupportedCardGalleryItemProps } from './SupportedCardGalleryItemProps';
import { GridBaseState } from '../../state';
import { FiltersMap } from '@wix/bex-core';
import { AddItemProps } from '@wix/design-system';
import { ActionCell } from '../ActionCell';
import { GridItem } from './GridItem';
import { GridDragAndDrop } from '../GridDragAndDropDndKit/GridDragAndDrop';
import type { Preset } from './Grid.types';

export interface UseRenderItemParams<T, F extends FiltersMap> {
  preset?: Preset;

  renderItem?: (
    item: T,
    index: number,
  ) => Partial<SupportedCardGalleryItemProps>;

  state: GridBaseState<T, F>;

  renderAddItem?: () => ReactElement<AddItemProps>;

  actionCell?: ActionCell<T, F>;

  dragAndDrop?: typeof GridDragAndDrop;
}

export function useRenderItem<T, F extends FiltersMap>(
  params: UseRenderItemParams<T, F>,
) {
  const {
    renderItem,
    state,
    renderAddItem,
    dragAndDrop,
    actionCell,
    preset = 'title',
  } = params;

  return useCallback<RenderItem>(
    (index, { itemKey: _itemKey, index2d } = {}) => (
      <GridItem
        state={state}
        index={index}
        rowIndex={index2d?.rowIndex}
        columnIndex={index2d?.columnIndex}
        renderItem={renderItem}
        actionCell={actionCell}
        renderAddItem={renderAddItem}
        dragAndDrop={dragAndDrop}
        preset={preset}
      />
    ),
    [renderItem, actionCell, renderAddItem, dragAndDrop, preset],
  );
}
