import {
  TableColumn as TableColumnWSR,
  TableColumn as WSRTableColumn,
} from '@wix/design-system/dist/types/Table';
import { NestedTableState } from '../../state';
import React from 'react';
import { useCreateWSRColumnBase } from '../../hooks/useCreateWSRColumnBase';
import { NestedTableFlatKeyedItem } from '../../state/NestedTableState/NestedTableFlatModeSectionState';
import { NestedTableFlatModeMainCell } from './NestedTableFlatModeMainCell';
import { useNestedTableActionCell } from './useNestedTableActionCell';
import { Column } from '../../model';

export interface UseFlatModeColumnsProps<C extends string> {
  state: NestedTableState<C>;
  horizontalScroll?: boolean;
  actionCellWidth?: string | number;
  actionCellProps?: Partial<Omit<TableColumnWSR<any>, 'render' | 'style'>>;
}

export function useFlatModeColumns<C extends string>(
  props: UseFlatModeColumnsProps<C>,
): WSRTableColumn<NestedTableFlatKeyedItem<C, any, any>>[] {
  const { state, actionCellProps, actionCellWidth, horizontalScroll } = props;

  const { toolbar } = state;

  const { selectedOrderedColumnsOrAll } = toolbar;

  const createWSRColumnBase = useCreateWSRColumnBase({ horizontalScroll, showFieldTypeIcons: toolbar.showFieldTypeIcons });

  const actionCellColumn = useNestedTableActionCell({
    state: state.flat,
    actionCellWidth,
    actionCellProps,
  });

  const mainColumn: WSRTableColumn<NestedTableFlatKeyedItem<C, any, any>> = {
    key: 'flat-mode-main-column',
    dataHook: 'flat-mode-main-column',
    title: '',
    width: '326px',
    ...state.mainColumn,
    style: undefined,
    render: ({ item }: NestedTableFlatKeyedItem<C, any, any>, rowNum) => (
      <NestedTableFlatModeMainCell item={item} rowNum={rowNum} />
    ),
  };

  const passedColumns = selectedOrderedColumnsOrAll.map((column) => {
    const { id, sortable } = column;
    return {
      ...column,
      sortDescending:
        sortable && id ? state.query.sort.getIsSortDescending(id) : undefined,
      render: (
        { item }: NestedTableFlatKeyedItem<any, any, any>,
        rowNum: number,
      ) => {
        return item.state.columns?.[id]?.(item.originalKeyedItem.item, rowNum);
      },
    };
  }) as Column[];

  return [
    ...[mainColumn, ...passedColumns].map((column, index, { length }) => {
      return {
        ...column,
        ...createWSRColumnBase(column, index, length),
      };
    }),
    ...(actionCellColumn ? [actionCellColumn] : []),
  ];
}
