import React, { useMemo } from 'react';
import { TagList } from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { AppliedFiltersTagListState } from './AppliedFiltersTagListState';
import { FiltersMap } from '@wix/bex-core';

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

function _AppliedFiltersTagList<T, F extends FiltersMap>(
  props: AppliedFiltersTagListProps<T, F>,
) {
  const { state, onClearButtonClicked, ...rest } = props;

  const { table, tags } = state;
  const { collection } = table;

  const { translate: t } = collection;

  const tagsMap = useMemo(
    () => new Map(tags.map((tag) => [tag.id, tag])),
    [tags],
  );

  return (
    <TagList
      dataHook="active-filter-tags"
      tags={tags}
      onTagRemove={(tagId) => {
        const tag = tagsMap.get(tagId);
        if (tag != null) {
          const { values, filter, filterProps } = tag;
          state._reportFilterToggleBiOnNextResult(filter, values);

          filter.remove(values, {
            emitEvents: ['change', 'refresh'],
          });

          values.forEach((value) => {
            filterProps?.onAppliedFilterTagRemove?.(value);
          });
        }
      }}
      size="small"
      maxVisibleTags={Infinity}
      actionButton={{
        label: t('cairo.clear'),
        onClick: () => {
          state.onClearButtonClick();
          onClearButtonClicked?.();
        },
      }}
      {...rest}
    />
  );
}

export const AppliedFiltersTagList = observer(_AppliedFiltersTagList);
