import React from 'react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { FilterProps } from '../../model';
import { useWixPatternsContainer, CursorQuery } from '@wix/bex-core/react';
import { MultiSelectCheckboxFilter } from '../MultiSelectCheckboxFilter';
import {
  Tag,
  TagExposure,
} 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, {
    paginationMode: 'cursor',
    queryName: [
      toolbarState.tagsCollectionState?.tagsManagementState.fqdnString,
      'tags',
      'filter',
    ].join('/'),
    fetchData: async ({ search = '', cursor, limit }: CursorQuery) => {
      const tagsManagementState =
        toolbarState.tagsCollectionState?.tagsManagementState;
      if (!tagsManagementState) {
        return { items: [], cursor: null, hasNext: false };
      }

      const result = await tagsManagementState.tagsService.queryTags(
        {
          fqdn: tagsManagementState.fqdnString,
          exposure: TagExposure.PRIVATE,
          query: {
            cursorPaging: { limit, cursor: cursor ?? null },
            ...(search ? { filter: { name: { $contains: search } } } : {}),
          },
        },
        {},
        {
          serverErrorOverride: () => ({
            message: t('cairo.tags.collectionPage.popover.loadTags.error.body'),
          }),
        },
      );

      return {
        items: result.items,
        cursor: result.cursor,
        hasNext: result.hasNext,
      };
    },
  });

  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);
