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

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

function _FiltersPanelSelectedFiltersSection<T, F extends FiltersMap>(
  props: FiltersPanelSelectedFiltersSectionProps<T, F>,
) {
  const { state } = props;

  const container = useWixPatternsContainer();

  const { translate: t } = container;

  const { pendingQuery } = state;

  useEffect(() => pendingQuery?.init(), []);

  if (pendingQuery == null) {
    return null;
  }

  const { trackedFiltersCount, hasChanged } = pendingQuery;

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

      <TextButton
        dataHook="clear-all-filters"
        size="small"
        onClick={() => {
          pendingQuery.clearSelected();
        }}
        disabled={!trackedFiltersCount}
      >
        {t('cairo.clear')}
      </TextButton>

      <Box align="right" flex={1}>
        <Button
          dataHook="apply-button"
          ellipsis
          disabled={!hasChanged}
          onClick={() => {
            pendingQuery.apply();
          }}
        >
          {t('cair.appliedFilters.Apply.CTA')}
        </Button>
      </Box>
    </>
  );
}

export const FiltersPanelSelectedFiltersSection = observer(
  _FiltersPanelSelectedFiltersSection,
);
