import { FiltersMap, RawFilters } from '@wix/bex-core';
import { TableState, ToolbarCollectionState } from '../../state';
import { Tag } from '@wix/bex-utils/@wix/ambassador-os-tags-v1-tag/types';
import { useSelector } from '../../useSelector';
import { TagsFilter } from './TagsFilter';
import React from 'react';

export const buildTagsFilterElement = <T, F extends FiltersMap>(
  state: ToolbarCollectionState<T, F>,
) => {
  const label = state.container.translate(
    'cairo.tags.filterPanel.dropdown.title',
  );

  return (
    <TagsFilter
      key={state.collection.filters.tags?.name}
      filter={state.collection.filters.tags!}
      accordionItemProps={{
        label,
      }}
      toolbarItemProps={{
        label,
      }}
    />
  );
};

export const useTagsFilter = <T, F extends FiltersMap>(
  state: TableState<T, F>,
) => {
  useSelector(() => state.toolbar.collection.filters.tags);

  const buildTagsFilterWrapper = () => {
    return buildTagsFilterElement(state.toolbar);
  };

  return { buildTagsFilter: buildTagsFilterWrapper };
};

export const extractTagsFilter = <F extends FiltersMap>(
  filters: RawFilters<F>,
  key: string = 'tags.privateTags.tagIds',
) => {
  const tagsFilterValue = filters.tags as Tag[] | undefined;
  if (!tagsFilterValue?.length) {
    return {};
  }

  const tagIds = tagsFilterValue.map((tag) => tag.id);

  return { [key]: tagIds };
};
