import React, { useEffect } from 'react';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { TableGridSwitchButton } from '../TableGridSwitchButton';
import {
  GridFolders,
  GridFoldersBasePropsWithoutPreset,
} from '../Grid/GridFolders';
import { TableGridSwitchFoldersState } from '../../state';
import { GridFoldersPresetProps } from '../Grid/GridFolders.types';
import { TableFolders, TableFoldersProps } from '../TableFolders';
import { InitialLoader } from '../InitialLoader';

export interface TableGridSwitchFoldersBaseProps<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
> extends Omit<
      GridFoldersBasePropsWithoutPreset<T1, F1, T2, F2>,
      'state' | 'dragAndDrop' | 'tableGridSwitchButton'
    >,
    Omit<
      TableFoldersProps<T1, F1, T2, F2>,
      'state' | 'dragAndDrop' | 'tableGridSwitchButton'
    > {
  /** A TableGridSwitchFoldersState instance created using [useTableGridSwitchFoldersState](./?path=/story/base-components-collections-tablegridswitchfolders-usetablegridswitchfolders--usetablegridswitchfolders). */
  state: TableGridSwitchFoldersState<T1, F1, T2, F2>;
}

export type TableGridSwitchFoldersProps<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
> = GridFoldersPresetProps<
  T1,
  T2,
  TableGridSwitchFoldersBaseProps<T1, F1, T2, F2>
>;

function _TableGridSwitchFolders<
  T1,
  F1 extends FiltersMap,
  T2,
  F2 extends FiltersMap,
>(props: TableGridSwitchFoldersProps<T1, F1, T2, F2>) {
  const { state } = props;
  const { gridFoldersState, tableFoldersState, toolbar } = state;

  const tableGridSwitchButton = (
    <TableGridSwitchButton state={state.viewTypeState} />
  );
  useEffect(() => {
    state.init();
  }, []);

  const {
    initTask: { status },
  } = state;

  const isLoading = status.isIdle || status.isLoading;
  return (
    <>
      {isLoading ? (
        <InitialLoader dataHook="initial-loader" state={toolbar} />
      ) : state.viewType === 'grid' ? (
        <GridFolders
          {...props}
          tableGridSwitchButton={tableGridSwitchButton}
          state={gridFoldersState}
        />
      ) : (
        <TableFolders
          {...props}
          tableGridSwitchButton={tableGridSwitchButton}
          state={tableFoldersState}
        />
      )}
    </>
  );
}

export const TableGridSwitchFolders = observer(_TableGridSwitchFolders);
