import {
  TableColumn as TableColumnWSR,
  TableColumn as WSRTableColumn,
} from '@wix/design-system/dist/types/Table';
import { NestedTableKeyedItem, NestedTableState } from '../../state';
import { NestedTableParentCell } from './NestedTableParentCell';
import React from 'react';
import { useCreateWSRColumnBase } from '../../hooks/useCreateWSRColumnBase';
import { useNestedTableActionCell } from './useNestedTableActionCell';
import type { NestedTableDragAndDrop } from '../NestedTableDragAndDrop/NestedTableDragAndDrop';
import { Column } from '../../model';
import { NestedTableMainColumnTitle } from './NestedTableMainColumnTitle';

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

export function useNestedModeColumns<C extends string>(
  props: UseNestedModeColumnsProps<C>,
): WSRTableColumn<NestedTableKeyedItem<any, any, any>>[] {
  const {
    state,
    actionCellProps,
    actionCellWidth,
    horizontalScroll,
    dragAndDrop,
  } = props;

  const { toolbar } = state;

  const { selectedOrderedColumnsOrAll } = toolbar;

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

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

  const mainColumn: WSRTableColumn<NestedTableKeyedItem<any, any, any>> = {
    key: 'nested-mode-main-column',
    dataHook: 'nested-mode-main-column',
    title: <NestedTableMainColumnTitle state={state} />,
    width: state.mainColumn?.width || '326px',
    style: undefined,
    render: (keyedItem, rowNum) => {
      if (keyedItem.item.originalKeyedItem) {
        return (
          <NestedTableParentCell
            state={keyedItem.item.state}
            item={keyedItem.item}
            rowNum={rowNum}
            dragAndDrop={dragAndDrop}
          />
        );
      }

      return null;
    },
  };

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

        return null;
      },
    };
  }) as Column[];

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