import React, { useEffect, useState } from 'react';
import { runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { ChangeOrderSmall } from '@wix/wix-ui-icons-common';
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';

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 [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={<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);
