import React, { useEffect, useState } from 'react';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { ChangeOrderSmall, ReorderSmall } from '@wix/wix-ui-icons-common/lazy';
import { MultiLevelSortingState, ToolbarCollectionState } from '../../state';
import { MultiLevelSortingPanelEntry } from '../MultiLevelSortingPanel';
import { CounterBadgeButton } from '../CounterBadgeButton';
import { usePageContext } from '@wix/bex-core/react';
import { ResponsiveButton } from '../ResponsiveButton/ResponsiveButton';
import { useBmHarmonyTheme } from '../../hooks/useBmHarmonyTheme';

export interface MultiLevelSortingCTAButtonProps<T, F extends FiltersMap> {
  state: ToolbarCollectionState<T, F>;
}

export function _MultiLevelSortingCTAButton<T, F extends FiltersMap>(
  props: MultiLevelSortingCTAButtonProps<T, F>,
) {
  const { state } = props;
  const {
    panels,
    container: { translate: t, isPanelLayout },
    toolbar: { responsive },
  } = state;

  const { modalsContainerRef } = usePageContext();
  const isHarmonyTheme = useBmHarmonyTheme();

  const [multiLevelSortingState] = useState(() =>
    runInAction(
      () =>
        (state.multiLevelSorting ??= new MultiLevelSortingState<T, F>({
          table: state,
          container: state.container,
          modalsContainerRef,
        })),
    ),
  );

  useEffect(() => multiLevelSortingState.init(), []);

  useEffect(() => {
    panels.registerSidePanel('multiLevelSorting', MultiLevelSortingPanelEntry);
  }, []);

  return (
    <CounterBadgeButton
      dataHook="multi-level-sorting-button-counter"
      count={multiLevelSortingState.sortListSize}
    >
      <ResponsiveButton
        state={responsive.actions}
        shouldShrink={!isPanelLayout}
        icon={isHarmonyTheme ? <ReorderSmall /> : <ChangeOrderSmall />}
        dataHook="multi-level-sorting-button"
        onClick={() => {
          const isOpen = panels.toggleSidePanel('multiLevelSorting');

          if (isOpen) {
            multiLevelSortingState.reportSidePanelOpen();
          } else {
            multiLevelSortingState.reportSidePanelClose({
              origin: 'Sort CTA',
            });
          }
        }}
      >
        {t('cairo.table.advanced-sorting.button.cta')}
      </ResponsiveButton>
    </CounterBadgeButton>
  );
}

export const MultiLevelSortingCTAButton = observer(_MultiLevelSortingCTAButton);
