import React, { useEffect } from 'react';
import { useToolbarCollectionContext } from '../ToolbarCollectionContext';
import { FilterProps } from '../../model';
import {
  useWixPatternsContainer,
  CursorQuery,
  OffsetQuery,
} 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 shouldAllowTagsPagination =
    toolbarState.tagsCollectionState?.tagsManagementState
      .shouldAllowTagsPagination ?? false;

  const paginationConfig = shouldAllowTagsPagination
    ? {
        paginationMode: 'cursor' as const,
        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 ?? undefined },
                ...(search
                  ? { filter: { name: { $startsWith: search } } }
                  : {}),
              },
            },
            {},
            {
              serverErrorOverride: () => ({
                message: t(
                  'cairo.tags.collectionPage.popover.loadTags.error.body',
                ),
              }),
            },
          );
          return {
            items: result.items,
            cursor: result.cursor,
            hasNext: result.hasNext,
          };
        },
      }
    : {
        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 };
        },
      };

  const tagsFilterCollection = useFilterCollection<Tag>(filter, {
    queryName: [
      toolbarState.tagsCollectionState?.tagsManagementState.fqdnString,
      'tags',
      'filter',
    ].join('/'),
    ...paginationConfig,
  });

  useEffect(() => {
    if (
      !shouldAllowTagsPagination &&
      toolbarState.tagsCollectionState?.tagsManagementState.items
    ) {
      tagsFilterCollection.refreshAllPages();
    }
  }, [
    shouldAllowTagsPagination,
    tagsFilterCollection,
    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);
