import React, { cloneElement, Fragment } from 'react';
import { HorizontalAvailableSpaceBox } from '../Responsive/HorizontalAvailableSpaceBox';
import { ToolbarItem } from '../ToolbarItem/ToolbarItem';
import { HorizontalOverflowBox } from '../Responsive/HorizontalOverflowBox';
import { ToolbarGroupScrollWidthBox } from './ToolbarGroupScrollWidthBox';
import { SearchOrCustomFilter } from './SearchOrCustomFilter';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { CollectionToolbarActionsGroupProps } from './CollectionToolbarActionsGroupProps';
import { InitialLoadingConditional } from '../InitialLoadingConditional';
import { CollectionToolbarSkeletonItem } from './CollectionToolbarSkeletonItem';

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

  const toolbarState = useToolbarCollectionContext();
  const {
    toolbar: { responsive },
  } = toolbarState;

  let child = (
    <Fragment>
      {left ? (
        <>
          {viewsToolbarItem && (
            <InitialLoadingConditional
              state={toolbarState}
              loadingElement={
                <CollectionToolbarSkeletonItem
                  dataHook="toolbar-views-skeleton"
                  width="100px"
                />
              }
            >
              {viewsToolbarItem}
            </InitialLoadingConditional>
          )}
          {filtersElement}
        </>
      ) : viewsToolbarItem ? (
        filtersElement
      ) : undefined}

      {MoreFiltersButton && (
        <ToolbarGroupScrollWidthBox state={responsive.filters} gap="SP2">
          <MoreFiltersButton />
        </ToolbarGroupScrollWidthBox>
      )}

      <ToolbarGroupScrollWidthBox state={responsive.actions} gap="SP2">
        {customColumns && showCustomColumnsOnTheLeft && customColumns}
        {multiLevelSorting}
        {exportButton &&
          cloneElement(exportButton, {
            toolbarType: 'default',
          })}
        {customColumns && !showCustomColumnsOnTheLeft && customColumns}
      </ToolbarGroupScrollWidthBox>

      {search && <SearchOrCustomFilter state={state} search={search} />}
    </Fragment>
  );

  child = (
    <HorizontalOverflowBox state={responsive.overflow} gap="SP2">
      {child}
    </HorizontalOverflowBox>
  );

  child = <ToolbarItem>{child}</ToolbarItem>;

  child = (
    <HorizontalAvailableSpaceBox state={responsive.actionsAvailableSpace}>
      {child}
    </HorizontalAvailableSpaceBox>
  );

  return child;
}
