import { useActionCellColumnBase } from '../ActionCell';
import {
  TableColumn as WSRTableColumn,
  TableColumn as TableColumnWSR,
} from '@wix/design-system/dist/types/Table';
import React, { useMemo } from 'react';
import { NestedTableKeyedItem, NestedTableNestedModeState } from '../../state';
import { NestedTableActionCell } from './NestedTableActionCell';
import { NestedTableFlatModeState } from '../../state/NestedTableState/NestedTableFlatModeState';
import { NestedTableFlatKeyedItem } from '../../state/NestedTableState/NestedTableFlatModeSectionState';

export interface UseNestedTableActionCellParams {
  state: NestedTableNestedModeState | NestedTableFlatModeState;
  actionCellWidth?: string | number;
  actionCellProps?: Partial<Omit<TableColumnWSR, 'render' | 'style'>>;
}

export function useNestedTableActionCell<
  A extends
    | NestedTableKeyedItem<any, any, any>
    | NestedTableFlatKeyedItem<any, any, any>,
>(params: UseNestedTableActionCellParams): WSRTableColumn<A> | null {
  const { state, actionCellProps, actionCellWidth } = params;

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

  return useMemo(() => {
    const isActionsColumnRequired = state.levels.some(
      (level) => level.actionCell,
    );

    if (!isActionsColumnRequired) {
      return null;
    }

    return {
      ...baseColumn,
      render: (keyedItem, rowNum) => {
        if (keyedItem.item.originalKeyedItem) {
          return (
            <NestedTableActionCell
              state={keyedItem.item.state}
              item={keyedItem.item.originalKeyedItem}
              rowNum={rowNum}
            />
          );
        }
        return null;
      },
    };
  }, [baseColumn, state]);
}
