import React, { cloneElement, Fragment } from 'react';
import { TableToolbar } from '@wix/design-system';
import { SearchOrCustomFilter } from './SearchOrCustomFilter';
import { CollectionToolbarActionsGroupProps } from './CollectionToolbarActionsGroupProps';
import { InitialLoadingConditional } from '../InitialLoadingConditional';
import { CollectionToolbarSkeletonItem } from './CollectionToolbarSkeletonItem';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { observer } from 'mobx-react-lite';
import { useIsMobile } from '../../hooks/useIsMobile';

function _CollectionToolbarActionsToolbarItemsGroup(
  props: CollectionToolbarActionsGroupProps,
) {
  const {
    state,
    left,
    viewsToolbarItem,
    filtersElement,
    MoreFiltersButton,
    multiLevelSorting,
    customColumns,
    exportButton,
    search,
    showCustomColumnsOnTheLeft,
  } = props;

  const toolbarState = useToolbarCollectionContext();

  const searchChild = search && (
    <SearchOrCustomFilter state={state} search={search} />
  );

  const isMobile = useIsMobile();

  return (
    <Fragment>
      {(!isMobile || !state._searchExpanded) && (
        <Fragment>
          {left ? (
            <>
              {viewsToolbarItem && (
                <InitialLoadingConditional
                  state={toolbarState}
                  loadingElement={
                    <CollectionToolbarSkeletonItem
                      dataHook="toolbar-views-skeleton"
                      width="100px"
                    />
                  }
                >
                  {viewsToolbarItem}
                </InitialLoadingConditional>
              )}
              {filtersElement}
            </>
          ) : viewsToolbarItem ? (
            filtersElement
          ) : undefined}
          {MoreFiltersButton && (
            <TableToolbar.Item>
              <MoreFiltersButton />
            </TableToolbar.Item>
          )}
          {customColumns && showCustomColumnsOnTheLeft && (
            <TableToolbar.Item>{customColumns}</TableToolbar.Item>
          )}
          {multiLevelSorting && (
            <TableToolbar.Item>{multiLevelSorting}</TableToolbar.Item>
          )}
          {exportButton && (
            <TableToolbar.Item>
              {cloneElement(exportButton, {
                toolbarType: 'default',
              })}
            </TableToolbar.Item>
          )}
          {customColumns && !showCustomColumnsOnTheLeft && (
            <TableToolbar.Item>{customColumns}</TableToolbar.Item>
          )}
        </Fragment>
      )}

      {searchChild}
    </Fragment>
  );
}

export const CollectionToolbarActionsToolbarItemsGroup = observer(
  _CollectionToolbarActionsToolbarItemsGroup,
);
