import React, { ReactElement, useEffect, useRef, useState } from 'react';
import { Box } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { ToolbarCollectionState } from '../../state';
import { InitialLoadingConditional } from '../InitialLoadingConditional';
import { CollectionToolbarSkeletonItem } from './CollectionToolbarSkeletonItem';
import { ToolbarLeftGroupState } from '../../state/Toolbar/ToolbarLeftGroupState';
import { ToolbarMode } from './toolbarModeUtils';

export interface CollectionToolbarLeftGroupProps<T, F extends FiltersMap> {
  state: ToolbarCollectionState<T, F>;
  left?: ReactElement;
  viewsToolbarItem?: ReactElement;
  filtersElement?: ReactElement;
  mode: ToolbarMode;
}

function _CollectionToolbarLeftGroup<T, F extends FiltersMap>(
  props: CollectionToolbarLeftGroupProps<T, F>,
) {
  const { state, left, viewsToolbarItem, filtersElement, mode } = props;

  const {
    toolbar: { responsive },
  } = state;

  const isLeftElementMode = mode === 'tabs' || mode === 'title';
  const shouldMeasure = isLeftElementMode && !responsive.responsiveDisabled;
  const container = useRef<HTMLDivElement | null>(null);

  const [leftGroupState] = useState(
    () =>
      new ToolbarLeftGroupState({
        responsive,
        mode,
        minWidth: mode === 'title' ? 50 : 140,
        getTabsState: () => state.tabs,
      }),
  );

  useEffect(() => {
    if (!shouldMeasure) {
      return;
    }
    responsive.leftGroupState = leftGroupState;
    const dispose = leftGroupState.init(container.current?.parentElement);
    return () => {
      dispose();
      responsive.leftGroupState = null;
    };
  }, [shouldMeasure]);

  const content = left ?? (
    <>
      {viewsToolbarItem && (
        <InitialLoadingConditional
          state={state}
          loadingElement={
            <CollectionToolbarSkeletonItem
              dataHook="toolbar-views-skeleton"
              width="100px"
            />
          }
        >
          {viewsToolbarItem}
        </InitialLoadingConditional>
      )}
      {!viewsToolbarItem ? filtersElement : undefined}
    </>
  );

  if (isLeftElementMode && !responsive.responsiveDisabled) {
    return (
      <Box ref={(element) => (container.current = element)}>{content}</Box>
    );
  }

  return <>{content}</>;
}

export const CollectionToolbarLeftGroup = observer(_CollectionToolbarLeftGroup);
