import React, { useEffect, useRef, useState } from 'react';
import { View, TouchableWithoutFeedback, Animated, Dimensions, BackHandler, TouchableOpacity } from 'react-native';
import { Event } from '../../../services';
import { Pressable } from '../../Pressable';
import { IItemsAlertBtn, IItemsAlert } from '../Alert.interface';
import {
   Container,
   Opacity,
   BtnContainer,
   FontAwesomeIconItem,
   TitleText,
   ModalContainer,
   Modal,
   TextContent,
   BtnAction,
} from './Alert.style';

const AlertObs = new Event<IItemsAlert>();

export const Alert: React.FunctionComponent<any> & { show: (options: IItemsAlert) => void } = () => {
   const offset = 0;
   const windowHeight = Dimensions.get('window').height;
   const [opened, setOpened] = useState(false);
   const [items, setItems] = useState<Partial<IItemsAlert>>({});
   const [heightItems, setHeightItems] = useState(0);
   const animation = useRef(new Animated.Value(1)).current;

   function close(): void {
      Animated.timing(animation, {
         toValue: 0,
         duration: 200,
         useNativeDriver: true,
      }).start(() => {
         setOpened(false);
      });
   }

   useEffect(() => {
      const obs = AlertObs.observable.subscribe((value) => {
         setItems(value);
         setOpened(true);
         animation.setValue(0);

         Animated.timing(animation, {
            toValue: 1,
            duration: 200,
            useNativeDriver: true,
         }).start();
      });

      return () => obs.unsubscribe();
   }, []);

   useEffect(() => {
      const backAction = (): boolean => {
         if (opened) {
            close();
            return true;
         }
         return false;
      };

      const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);

      return () => backHandler.remove();
   }, [opened]);

   function onPress(btn: IItemsAlertBtn): void {
      if (btn.onPress) btn.onPress();
      close();
   }

   return (
      <>
         <Container visible={opened} animationType="fade" transparent>
            <Opacity />
            <ModalContainer>
               <TouchableWithoutFeedback onPress={close} testID="background-alert">
                  <View
                     style={{
                        position: 'absolute',
                        width: '100%',
                        height: '100%',
                     }}
                  />
               </TouchableWithoutFeedback>

               <Modal>
                  {items.icon && <FontAwesomeIconItem icon={items.icon} color={items.iconColor} />}

                  {items.title &&
                     (typeof items.title === 'string' ? (
                        <TitleText color={items.titleColor || 'black'}>{items.title}</TitleText>
                     ) : (
                        items.title
                     ))}

                  {items.message &&
                     (typeof items.message === 'string' ? (
                        <TextContent>Após deletado, não será possivel RECUPERA-LO</TextContent>
                     ) : (
                        items.message
                     ))}

                  <BtnContainer>
                     {items.buttons &&
                        items.buttons.map((btn, index) => (
                           <Pressable
                              key={`btn-${index}`}
                              testID={`alert-btn-${index}`}
                              onPress={() => onPress(btn)}
                              ripple
                           >
                              <BtnAction color={btn.color || '#444'}>{btn.text}</BtnAction>
                           </Pressable>
                        ))}
                  </BtnContainer>
               </Modal>
            </ModalContainer>
         </Container>
      </>
   );
};

Alert.show = (options: IItemsAlert) => {
   AlertObs.set(options);
};
