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

export interface UseRenderFolderItemParams<T, F extends FiltersMap> {
  folderPreset?: 'full' | 'title';

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

  state: GridBaseState<T, F>;

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

  folderActionCell?: ActionCell<T, F>;

  dragAndDrop?: typeof GridDragAndDrop;
}

export function useRenderFolderItem<T, F extends FiltersMap>(
  params: UseRenderFolderItemParams<T, F>,
) {
  const {
    state,
    folderPreset = 'title',
    renderFolderItem,
    dragAndDrop,
    folderActionCell,
  } = params;

  return useCallback<RenderItem>(
    (index, { itemKey: _itemKey, index2d } = {}) => {
      const renderType = state.getItemRenderTypeAt(index);

      if (renderType === null) {
        return null;
      }

      if (renderType === 'trailing') {
        return null;
      }

      let child = (
        <GridCardItem
          state={state}
          index={index}
          rowIndex={index2d?.rowIndex}
          columnIndex={index2d?.columnIndex}
          keyedItem={renderType}
          renderItem={(item, i) => ({
            backgroundImageNode: <FolderIcon />,
            imagePlacement: 'side',
            ...renderFolderItem?.(item, i),
          })}
          preset={folderPreset}
          actionCell={folderActionCell}
        />
      );

      if (dragAndDrop) {
        const { DraggableCard } = dragAndDrop;
        child = (
          <DraggableCard
            id={renderType.key}
            index={renderType.index}
            state={state}
          >
            {child}
          </DraggableCard>
        );
      }

      return child;
    },
    [dragAndDrop?.DraggableCard],
  );
}
