import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Animated, Keyboard, Modal, ScrollView, View, Dimensions, BackHandler } from 'react-native';
import { RFValue } from 'react-native-responsive-fontsize';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';
import { FormHandles } from '@unform/core';
import { useImmer } from 'use-immer';
import { Button } from '../../../Button/native';
import { Pressable } from '../../../Pressable';
import { IPageListingChildrenProps } from '../PageListing.interface';
import { Container, ClearBtn, FilterTitle, HeaderFilters, FilterBtn, BackBtn } from './FiltersContainer.style';

export function FiltersContainer(props: IPageListingChildrenProps): JSX.Element {
   const { FiltersComponent, filterMobileOpen, closeFilters, setFilterMobileOpen, viewList } = props;
   const { filters, setFilters } = viewList;
   const [filtersTemp, setFiltersTemp] = useImmer<any>(filters);
   const [hideScreen, setHideScreen] = useState(true);
   const scrollRef = useRef<any>();
   const formRef = useRef<FormHandles>();
   const animatedToggleFilter = useRef(new Animated.Value(1)).current;

   const handleFilters = useCallback(function handleFilters(data): void {
      setFilters(() => data);
      closeFilters();
      Keyboard.dismiss();
   }, []);

   const applyFilters = useCallback(
      function applyFilters() {
         formRef.current.submitForm();
      },
      [filtersTemp],
   );

   useLayoutEffect(() => {
      if (filterMobileOpen) {
         setHideScreen(false);
         animatedToggleFilter.setValue(0);
      } else {
         Animated.timing(animatedToggleFilter, {
            toValue: 0,
            duration: 200,
            useNativeDriver: true,
         }).start(() => {
            setHideScreen(true);
         });
      }
   }, [filterMobileOpen]);

   const clearFilters = useCallback(function clearFilters() {
      closeFilters();
      setFilters(() => ({}));
   }, []);

   const onRequestClose = useCallback(function onRequestClose(): void {
      Keyboard.dismiss();
      formRef.current.reset();
      formRef.current.setData(filters);
      closeFilters();
   }, []);

   function onShow(): void {
      Animated.timing(animatedToggleFilter, {
         toValue: 1,
         duration: 200,
         useNativeDriver: true,
      }).start();
   }

   return (
      <Modal visible={!hideScreen} onRequestClose={onRequestClose} transparent onShow={onShow}>
         <Container
            style={{
               opacity: animatedToggleFilter,
               transform: [
                  {
                     translateX: animatedToggleFilter.interpolate({
                        inputRange: [0, 1],
                        outputRange: [200, 0],
                     }),
                  },
                  {
                     translateY: hideScreen ? Dimensions.get('window').height : 0,
                  },
               ],
            }}
            testID="filters-container"
         >
            <View style={{ flex: 1 }}>
               <ScrollView
                  ref={scrollRef}
                  testID="filters-scroll"
                  keyboardShouldPersistTaps="handled"
                  keyboardDismissMode="on-drag"
                  onScrollBeginDrag={Keyboard.dismiss}
                  onTouchStart={Keyboard.dismiss}
               >
                  <HeaderFilter clearFilters={clearFilters} onRequestClose={onRequestClose} />
                  <FiltersComponent handleFilters={handleFilters} filters={filters} formRef={formRef} />
               </ScrollView>
               <FilterBtn>
                  <Button onPress={applyFilters} variant="primary" rounded>
                     FILTRAR
                  </Button>
               </FilterBtn>
            </View>
         </Container>
      </Modal>
   );
}

const HeaderFilter = React.memo(function HeaderFilter({ clearFilters, onRequestClose }: any): any {
   return (
      <>
         <BackBtn onPress={() => onRequestClose()} ripple>
            <FontAwesomeIcon icon={faArrowLeft} color="black" size={RFValue(20)} />
         </BackBtn>

         <HeaderFilters>
            <FilterTitle>Filtros</FilterTitle>
            <Pressable onPress={clearFilters} testID="clear-filters" style={{ padding: 10 }}>
               <ClearBtn>LIMPAR FILTROS</ClearBtn>
            </Pressable>
         </HeaderFilters>
      </>
   );
});
