import React, { useCallback, useImperativeHandle } from 'react';
import { useMemoImmer } from '@devesharp/react-hooks/lib/useMemoImmer';
import remove from 'lodash/remove';
import { ETagFilterType, IPropsTagFilter, ITagFilter, ITagFilterRef } from './TagsFilters.interface';
import { TagsFiltersStyle } from './TagsFilters.style';
import { generateTagsFilters } from './TagsFilters.utils';

export const TagsFilters = React.forwardRef<ITagFilterRef, IPropsTagFilter>(function TagsFilters(
   { filters, filtersSchema, removeTag, fullColor },
   ref,
): JSX.Element {
   const tags: ITagFilter[] = useMemoImmer(() => generateTagsFilters(filters, filtersSchema), [filters, filtersSchema]);

   useImperativeHandle(
      ref,
      () => ({
         tagsCount: tags.length,
      }),
      [tags],
   );

   const setEmptyField = useCallback(
      function setEmptyField(tag: ITagFilter): void {
         switch (tag.type) {
            case 'checkbox':
               removeTag(
                  tag.key,
                  remove([...tag.values], (n) => n !== tag.checkboxValue),
               );
               break;

            case ETagFilterType.CheckBoxKey:
               removeTag(tag.key, {
                  ...tag.values,
                  [tag.checkboxValue]: false,
               });
               break;

            case 'location':
               removeTag(
                  tag.key,
                  tag.values
                     .split('_')
                     .filter((l) => l !== tag.locationValue)
                     .join('_'),
               );
               break;

            case 'select':
            case 'input':
               removeTag(tag.key, tag.default);
               break;
         }
      },
      [removeTag],
   );

   return (
      <TagsFiltersStyle fullColor={fullColor}>
         {!!tags.length && (
            <div className="tag-filters" data-testid="tag-filters">
               <div className="search-tags">
                  {tags.map((tag, index) => (
                     <TagFilter key={`tag-${index}`} setEmptyField={setEmptyField} tag={tag} />
                  ))}
               </div>
            </div>
         )}
      </TagsFiltersStyle>
   );
});

function TagFilter({ tag, setEmptyField }): JSX.Element {
   return (
      <div className="tag" onClick={() => setEmptyField(tag)} data-testid={`tag-${tag.value}`}>
         <span>
            {tag.prefix}
            {tag.value}
            {tag.suffix}
         </span>
      </div>
   );
}
