import { observer } from 'mobx-react-lite';
import { GridCardItem } from './GridCardItem';
import React, { ReactElement } from 'react';
import { ActionCellAPI, GridBaseState } from '../../state';
import { FiltersMap } from '@wix/bex-core';
import { AddItemProps } from '@wix/design-system';
import { ActionCellProps } from '../ActionCell';
import { SupportedCardGalleryItemProps } from './SupportedCardGalleryItemProps';
import { GridDragAndDrop } from '../GridDragAndDropDndKit/GridDragAndDrop';
import type { Preset } from './Grid.types';

export interface GridItemProps<T, F extends FiltersMap> {
  state: GridBaseState<T, F>;
  preset?: Preset;
  renderAddItem?: () => ReactElement<AddItemProps>;
  renderItem?: (
    item: T,
    index: number,
  ) => Partial<SupportedCardGalleryItemProps>;

  index: number;
  rowIndex?: number;
  columnIndex?: number;
  actionCell?:
    | ActionCellProps
    | ((item: T, index: number, api: ActionCellAPI<T, F>) => ActionCellProps);
  dragAndDrop?: typeof GridDragAndDrop;
  isOverlay?: boolean;
}

function _GridItem<T, F extends FiltersMap>(props: GridItemProps<T, F>) {
  const {
    state,
    preset,
    index,
    rowIndex,
    columnIndex,
    renderItem,
    renderAddItem,
    actionCell,
    dragAndDrop,
    isOverlay,
  } = props;
  const renderType = state.getItemRenderTypeAt(index);

  const {
    collection: {
      query: { hasNonPersistentActiveFilters },
    },
  } = state;

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

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

    return (
      <div
        key="add-item"
        data-hook="grid-add-item-container"
        style={{ height: '100%' }}
        onClick={() => state.onAddItemClick()}
      >
        {renderAddItem?.()}
      </div>
    );
  }

  let child = (
    <GridCardItem
      state={state}
      index={index}
      rowIndex={rowIndex}
      columnIndex={columnIndex}
      keyedItem={renderType}
      renderItem={renderItem}
      actionCell={actionCell}
      preset={preset}
    />
  );

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

  return child;
}

export const GridItem = observer(_GridItem);
