import React, { useCallback, useImperativeHandle, useMemo } from 'react';
import { format } from 'date-fns';
import * as _ from 'lodash';
import moment from 'moment';
import { useMemoImmer } from '../../../hooks/useMemoImmer';
import { isEmpty, NumberFormat, convertStringToDate } from '../../../services';
import { IPropsTagFilter, ITagFilter, ITagFilterRef } from '../TagsFilters.interface';
import { generateTagsFilters } from '../TagsFilters.utils';
import { TagsFiltersStyle } from './TagsFilters.style';

export const TagsFilters = React.forwardRef<ITagFilterRef, IPropsTagFilter>(function TagsFilters(
   { filters, filtersSchema, removeTag },
   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 'location':
            removeTag(
               tag.key,
               tag.values
                  .split('_')
                  .filter((l) => l !== tag.locationValue)
                  .join('_'),
            );
            break;

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

   return (
      <TagsFiltersStyle>
         {!!tags.length && (
            <div className="tag-filters" data-cy="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-cy={`tag-${tag.value}`}
         data-testid={`tag-${tag.value}`}
      >
         <span>
            <b>{tag.prefix}</b>
            {tag.value}
            {tag.suffix}
         </span>
      </div>
   );
}
