import { Box, Text, TextButton } from '@wix/design-system';
import React from 'react';
import { ToolbarCollectionState } from '../../state';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { runInAction } from 'mobx';

export interface FiltersPanelAppliedFiltersSectionProps<
  T,
  F extends FiltersMap,
> {
  state: ToolbarCollectionState<T, F>;
  onClearButtonClicked?: () => unknown;
}

function _FiltersPanelAppliedFiltersSection<T, F extends FiltersMap>(
  props: FiltersPanelAppliedFiltersSectionProps<T, F>,
) {
  const { state, onClearButtonClicked } = props;

  const { collection } = state;

  const { translate: t, query } = collection;
  const { nonPersistentCustomFiltersCount } = query;

  return (
    <>
      <Text weight="bold" dataHook="applied-filters" size="small">
        {t('cairo.appliedFilters', {
          num: nonPersistentCustomFiltersCount,
        })}
      </Text>

      <Box align="right" flex={1}>
        <TextButton
          dataHook="clear-all-filters"
          size="small"
          onClick={() => {
            runInAction(() => {
              const {
                query: { nonPersistentCustomFilters },
              } = collection;
              collection.emitter.emit('beforeClearFilters', {
                origin: 'sidebar',
              });
              nonPersistentCustomFilters
                .filter((filter) => !filter._hideFromToolbar)
                .forEach((filter) => {
                  filter?.reset({ emitEvents: ['change', 'refresh'] });
                });
            });
            onClearButtonClicked?.();
            state.sidePanel.focus.modalElement?.focus();
          }}
          disabled={!nonPersistentCustomFiltersCount}
        >
          {t('cairo.clear')}
        </TextButton>
      </Box>
    </>
  );
}

export const FiltersPanelAppliedFiltersSection = observer(
  _FiltersPanelAppliedFiltersSection,
);
