import React, { cloneElement, Fragment, useEffect } from 'react';
import { Box } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { ToolbarItem } from '../ToolbarItem/ToolbarItem';
import { ToolbarGroupScrollWidthBox } from './ToolbarGroupScrollWidthBox';
import { SearchOrCustomFilter } from './SearchOrCustomFilter';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { CollectionToolbarActionsGroupProps } from './CollectionToolbarActionsGroupProps';
import { InitialLoadingConditional } from '../InitialLoadingConditional';
import { CollectionToolbarSkeletonItem } from './CollectionToolbarSkeletonItem';
import { ToolbarOverflowMenu } from './ToolbarOverflowMenu';
import { useToolbarOverflowItems } from './useToolbarOverflowItems';
import { LAYOUT_SWITCH_BUTTON_WIDTH } from '../../state/Toolbar/toolbarResponsiveConstants';

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

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

  const overflowItems = useToolbarOverflowItems(toolbarState, {
    customColumns,
    multiLevelSorting,
    exportButton,
    importButton,
    MoreFiltersButton,
    viewTypeState,
  });

  const overflowItemCount =
    overflowItems.primaryItems.length +
    overflowItems.secondaryItems.length +
    (overflowItems.layoutSwitchConfig ? 1 : 0);

  // Don't show a "More" menu for a single item — keep it as an inline icon.
  const shouldOverflow = responsive._shouldOverflow && overflowItemCount > 1;

  // Track width of non-group content hidden during overflow so the algorithm
  // doesn't overestimate available space when deciding whether to exit overflow.
  // Tied to effective shouldOverflow (not just _shouldOverflow) so the single-item
  // bypass doesn't cause a mismatch between DOM and algorithm.
  useEffect(() => {
    responsive._overflowHiddenContentWidth =
      tableGridSwitchButton && shouldOverflow ? LAYOUT_SWITCH_BUTTON_WIDTH : 0;
  }, [responsive, !!tableGridSwitchButton, shouldOverflow]);

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

      {!shouldOverflow && tableGridSwitchButton}

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

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

      {shouldOverflow && (exportButton || importButton) && (
        <Box display="none">
          {exportButton &&
            cloneElement(exportButton, { toolbarType: 'default' })}
          {importButton &&
            cloneElement(importButton, { toolbarType: 'default' })}
        </Box>
      )}

      {shouldOverflow && (
        <ToolbarOverflowMenu
          primaryItems={overflowItems.primaryItems}
          secondaryItems={overflowItems.secondaryItems}
          layoutSwitchConfig={overflowItems.layoutSwitchConfig}
        />
      )}

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

  child = (
    <Box
      ref={(element) => {
        responsive._contentElement = element;
      }}
      dataHook="horizontal-overflow-box"
      minWidth={0}
      direction="horizontal"
      gap="SP2"
    >
      {child}
    </Box>
  );

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

  child = (
    <Box
      ref={(element) => {
        responsive._measurementElement = element;
      }}
      minWidth={0}
      flex={1}
      align="right"
      direction="horizontal"
    >
      {child}
    </Box>
  );

  return child;
}

export const CollectionToolbarActionsGroupResponsiveLayout = observer(
  _CollectionToolbarActionsGroupResponsiveLayout,
);
