import {
  ActionCell,
  useActionCellColumnBase,
  useRenderActionCellColumn,
} from '../ActionCell';
import { FoldersAndItemsCollectionsState } from '../../state/FoldersAndItemsCollectionsState';
import { FiltersMap } from '@wix/bex-core';
import { TableColumn as TableColumnWSR } from '@wix/design-system/dist/types/Table';
import { useMemo } from 'react';
import { isFolderKeyedItem, isItemKeyedItem, RowKeyedItem } from '../../state';

export interface UseOrFolderActionCellColumnParams<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
> {
  state: FoldersAndItemsCollectionsState<T1, F1, T2, F2>;
  actionCell?: ActionCell<T1, F1>;
  actionCellWidth?: string | number;
  actionCellProps?: Partial<Omit<TableColumnWSR, 'render' | 'style'>>;
  folderActionCell?: ActionCell<T2, F2>;
}

export function useOrFolderActionCellColumn<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(
  params: UseOrFolderActionCellColumnParams<T1, F1, T2, F2>,
): TableColumnWSR<RowKeyedItem<T1, T2>> | null {
  const {
    state: { items, folders },
    actionCell,
    folderActionCell,
    actionCellProps,
    actionCellWidth,
  } = params;

  const baseColumn = useActionCellColumnBase({
    actionCellProps,
    actionCellWidth,
  });

  const renderItem = useRenderActionCellColumn({
    actionCell,
    sticky: true,
    collection: items,
  });

  const renderFolder = useRenderActionCellColumn({
    actionCell: folderActionCell,
    sticky: true,
    collection: folders,
  });

  return useMemo(() => {
    if (renderItem == null && renderFolder == null) {
      return null;
    }

    return {
      ...baseColumn,
      render: (keyedItem, rowNum) => {
        if (isItemKeyedItem(keyedItem)) {
          return renderItem?.(keyedItem.item.originalKeyedItem, rowNum);
        }

        if (isFolderKeyedItem(keyedItem)) {
          return renderFolder?.(keyedItem.item.originalKeyedItem, rowNum);
        }

        return null;
      },
    };
  }, [baseColumn, renderItem, renderFolder]);
}
