import React, { useCallback, useEffect, useImperativeHandle, useMemo } from 'react';
import { ScrollView, View } from 'react-native';
import * as _ from 'lodash';
import { useDeepCompareEffectNoCheck } from 'use-deep-compare-effect';
import { useDidUpdateDeepCompareLayoutEffect } from '../../../hooks/useDidUpdateDeepCompareLayoutEffect';
import { useMemoImmer } from '../../../hooks/useMemoImmer';
import { Flex } from '../../Flex/native';
import { RSValue } from '../../RFValue';
import { TextNative } from '../../TextNative';
import { IPropsTagFilter, ITagFilter, ITagFilterRef } from '../TagsFilters.interface';
import { generateTagsFilters } from '../TagsFilters.utils';
import { Container, FiltersBtn, Tag, Close } from './TagsFilters.style';

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

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

   useDeepCompareEffectNoCheck(() => {
      if (onChange) onChange(tags);
   }, [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 <TagFiltersRender tags={tags} setEmptyField={setEmptyField} />;
});

const TagFiltersRender = React.memo(function TagFiltersRender({ tags, setEmptyField }: any): JSX.Element {
   return (
      <Container testID="filters-tags">
         <Flex>
            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
               <Flex horizontal style={{ paddingHorizontal: RSValue(10) }}>
                  {!!tags.length &&
                     tags.map((tag: any, i: number) => (
                        <TagFilter tag={tag} setEmptyField={setEmptyField} key={`tag-${tag.value}`} />
                     ))}
               </Flex>
            </ScrollView>
         </Flex>
      </Container>
   );
}, _.isEqual);

const TagFilter = React.memo(function TagFilter({ tag, setEmptyField }: any): JSX.Element {
   return (
      <Tag testID={`tag-${tag.value}`} onPress={() => setEmptyField(tag)} ripple>
         <TextNative color="white" size={13}>
            {tag.prefix}
            {tag.value}
            {tag.suffix}
         </TextNative>
         <Close>×</Close>
      </Tag>
   );
}, _.isEqual);
