import React, { useEffect } from 'react';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { getToolbarCollectionFeaturesInitializers } from '../../state/getToolbarCollectionFeaturesInitializers';
import { TableFoldersLayout } from './TableFoldersLayout';
import { TableProvider } from '../../providers';
import {
  TableFoldersContent,
  TableFoldersContentProps,
} from './TableFoldersContent';
import { useTableFoldersSyncProps } from './useTableFoldersSyncProps';
import { MultiCollectionBulkActionModal } from '../BulkAction';
import { runInAction } from 'mobx';
import { minimalRequiredWdsRuntimeCheck } from '../../minimalRequiredWdsRuntimeCheck';

export interface TableFoldersProps<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
> extends TableFoldersContentProps<T1, F1, T2, F2> {
  dataHook?: string;
  rowHeight?: number;
  estimatedRowHeight?: number;
}

function _TableFolders<T1, F1 extends FiltersMap, T2, F2 extends FiltersMap>(
  props: TableFoldersProps<T1, F1, T2, F2>,
) {
  const {
    state,
    multiLevelSorting,
    rowHeight,
    estimatedRowHeight,
    exportModal,
    bulkActionModal,
  } = props;

  if (process.env.NODE_ENV !== 'production') {
    // need this version because of style fixes on the WSR side
    minimalRequiredWdsRuntimeCheck({
      required: '^1.64.1',
      requiredBy: 'WixPatterns/TableFolders',
    });
  }

  useEffect(() => {
    runInAction(() => {
      state.virtual.rowHeight = rowHeight;
    });
  }, [rowHeight]);

  useEffect(() => {
    if (estimatedRowHeight == null) {
      return;
    }
    runInAction(() => {
      state.virtual.estimatedRowHeight = estimatedRowHeight;
    });
  }, [estimatedRowHeight]);

  useTableFoldersSyncProps(props);

  useEffect(
    () =>
      state.init({
        featuresInitializers: getToolbarCollectionFeaturesInitializers(props),
        hasMultiLevelSorting: multiLevelSorting !== undefined,
      }),
    [],
  );

  return (
    <TableFoldersLayout {...props} state={state}>
      <TableProvider value={state.table}>
        <TableFoldersContent {...props} />
      </TableProvider>
      {exportModal ?? state.toolbar.featuredComponents.exportModal.value}
      {bulkActionModal && (
        <MultiCollectionBulkActionModal
          state={state.toolbar}
          bulkActionModal={bulkActionModal}
        />
      )}
    </TableFoldersLayout>
  );
}

export const TableFolders = observer(_TableFolders);
