import React, { ReactElement } from 'react';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { GridFoldersState } from '../../state';
import { useRenderItem } from './useRenderItem';
import { useRenderFolderItem } from './renderFolderItem';
import { GridFoldersFolderSection } from './GridFoldersFolderSection';
import { GridFoldersItemsSection } from './GridFoldersItemsSection';
import { SupportedCardGalleryItemProps } from './SupportedCardGalleryItemProps';
import { ActionCell } from '../ActionCell';
import { AddItemProps } from '@wix/design-system';
import { GridFoldersLoadingSection } from './GridFoldersLoadingSection';
import { GridDragAndDrop } from '../GridDragAndDropDndKit/GridDragAndDrop';

export interface GridFoldersSectionsGroupProps<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
> {
  dataHook?: string;

  state: GridFoldersState<T1, F1, T2, F2>;

  itemsSectionTitle?: string;
  foldersSectionTitle?: string;

  renderItem?: (
    item: T1,
    index: number,
  ) => Partial<SupportedCardGalleryItemProps>;
  actionCell?: ActionCell<T1, F1>;
  renderAddItem?: () => ReactElement<AddItemProps>;

  renderFolderItem?: (
    item: T2,
    index: number,
  ) => Partial<SupportedCardGalleryItemProps>;
  folderActionCell?: ActionCell<T2, F2>;
  renderFolderAddItem?: () => ReactElement<AddItemProps>;

  dragAndDrop?: typeof GridDragAndDrop;
}

function _GridFoldersSectionsGroup<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(props: GridFoldersSectionsGroupProps<T1, F1, T2, F2>) {
  const { state, itemsSectionTitle, foldersSectionTitle } = props;

  const renderItem = useRenderItem({
    ...props,
    state: state.items,
  });

  const renderFolderItem = useRenderFolderItem({
    ...props,
    state: state.folders,
  });

  const { showLoadingSection } = state;

  return showLoadingSection ? (
    <GridFoldersLoadingSection state={state} />
  ) : (
    <>
      {state.showFoldersSection && (
        <GridFoldersFolderSection
          state={state}
          sectionTitle={foldersSectionTitle}
          renderItem={renderFolderItem}
        />
      )}
      {state.showItemsSection && (
        <GridFoldersItemsSection
          state={state}
          renderItem={renderItem}
          sectionTitle={itemsSectionTitle}
        />
      )}
    </>
  );
}

export const GridFoldersSectionsGroup = observer(_GridFoldersSectionsGroup);
