import React, { useEffect } from 'react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { FilterProps } from '../../model';
import { useWixPatternsContainer, OffsetQuery } from '@wix/bex-core/react';
import { MultiSelectCheckboxFilter } from '../MultiSelectCheckboxFilter';
import { Tag } from '@wix/bex-utils/@wix/ambassador-os-tags-v1-tag/types';
import { useFilterCollection } from '../../hooks/useFilterCollection';
import { observer } from 'mobx-react-lite';

type TagsFilterType = Tag[];
interface TagsFilterProps extends FilterProps<TagsFilterType> {}

export const _TagsFilter = ({ filter }: TagsFilterProps) => {
  const toolbarState = useToolbarCollectionContext();
  const { translate: t } = useWixPatternsContainer();

  const tagsFilterCollection = useFilterCollection(filter, {
    queryName: [
      toolbarState.tagsCollectionState?.tagsManagementState.fqdnString,
      'tags',
      'filter',
    ].join('/'),
    fetchData: async ({ search = '' }: OffsetQuery) => {
      const filteredItems = (
        toolbarState.tagsCollectionState?.tagsManagementState.items || []
      ).filter((tag: Tag) =>
        tag.name?.toLowerCase().includes(search.toLowerCase()),
      );

      return {
        items: filteredItems,
        total: filteredItems.length,
      };
    },
  });

  useEffect(() => {
    if (toolbarState.tagsCollectionState?.tagsManagementState.items) {
      tagsFilterCollection.refreshAllPages();
    }
  }, [toolbarState.tagsCollectionState?.tagsManagementState.items]);

  if (!toolbarState.tagsCollectionState) {
    return null;
  }

  return (
    <MultiSelectCheckboxFilter
      collection={tagsFilterCollection}
      filter={filter}
      popoverProps={{ appendTo: 'window' }}
      placeholder={t('cairo.tags.filterPanel.dropdown.placeholder')}
      renderItem={(tag: Tag) => ({
        title: tag.name as string,
        id: tag.id,
      })}
    />
  );
};

export const TagsFilter = observer(_TagsFilter);
