import React, { useMemo, useState } from 'react';
import { FiltersMap, KeyedItem } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { CollectionTable, CollectionTableBaseProps } from '../CollectionTable';
import { useTableSectionRow } from './useTableSectionRow';
import { TableState } from '../../state';
import { RenderSection } from '../CollectionSectionHeader';
import { TableSectionsState } from './TableSectionsState';

export interface TableSectionsProps<T, F extends FiltersMap>
  extends CollectionTableBaseProps<T, F> {
  renderSection: RenderSection<T>;
  table: TableState<T, F>;
}

const _TableSections = <T, F extends FiltersMap>({
  renderSection,
  table,
  columns,
  rowDetails,
  ...collectionTableProps
}: TableSectionsProps<T, F>) => {
  const [state] = useState(() => new TableSectionsState(table, renderSection));

  const columnsWithSections = useMemo(
    () =>
      columns.map((column) => ({
        ...column,
        render: (item: T, rowNum: number) => {
          const keyedItem = state.sectionsKeyedItems[rowNum];
          if (keyedItem && state.isSectionRow(keyedItem)) {
            return null;
          }

          return column.render(item, rowNum);
        },
      })),
    [columns],
  );

  const wrappedRowDetails = useMemo(() => {
    if (!rowDetails) {
      return undefined;
    }
    return (rowData: KeyedItem<T>, rowNum: number) => {
      if (state.isSectionRow(rowData)) {
        return null;
      }
      return rowDetails(rowData, rowNum);
    };
  }, [rowDetails, state]);

  const TableSectionsTrElement = useTableSectionRow(state);

  return (
    <CollectionTable
      {...collectionTableProps}
      rowDetails={wrappedRowDetails}
      state={state.table}
      columns={columnsWithSections}
      keyedItems={state.sectionsKeyedItems}
      TrElementType={TableSectionsTrElement}
      isRowDisabled={(keyedItem) => {
        return state.isSectionRow(keyedItem);
      }}
    />
  );
};

export const TableSections = observer(_TableSections);

export type TableSectionsProp<T> = {
  TableSections: typeof TableSections;
  renderSection: RenderSection<T>;
};
