import React, { useState, useEffect, createContext, useContext, Fragment, useRef } from 'react';
import Styled from 'styled-components/native';
import IndependentCreator from '~/Generated/Independent';
import { View, BackHandler, Modal, SafeAreaView, Platform } from 'react-native';
import { ContextInitialValue, PopupContext } from './Context';
import { Util } from '~/Utils/utils';
import AnimatedContainer from '../AnimatedContainer';

const PopupProviderPopup = ({popPopup=()=>{}, popupObj={}}) => {
    const animRef = useRef();
    const [refresh, setRefresh] = useState(0);

    return (
        <AnimatedContainer visible={true} fullScreen={true} animation="slideUp" fadeIn={true} 
            ref={animRef}
            onRequestClose={() => {
                console.log('close...');
                if(animRef && animRef.current && animRef.current.hide) {
                    animRef.current.hide(() => {
                        popupObj.onClose();
                        popPopup();
                    });
                } else {
                    popupObj.onClose();
                    popPopup();
                }
                return true;
            }}>
            <View style={{ width:'100%', height:'100%' }}>
                <popupObj.Popup {...popupObj.props} popup={{
                    select: (result) => {
                        console.log('onSelect.....');
                        if(animRef && animRef.current && animRef.current.hide) {
                            animRef.current.hide(() => {
                                popupObj.onSelect(result);
                                popPopup();
                            });
                        } else {
                            popupObj.onSelect(result);
                            popPopup();
                        }
                    }, 
                    close: () => {
                        console.log('onClose.....');
                        if(animRef && animRef.current && animRef.current.hide) {
                            animRef.current.hide(() => {
                                popupObj.onClose();
                                popPopup();
                            });
                        } else {
                            popupObj.onClose();
                            popPopup();
                        }
                    }
                }} />
            </View>
        </AnimatedContainer>
    )
} 

export const PopupProvider = ({children}) => {
    const popup = useContext(PopupContext);
    const [popupElements, setPopupElements] = useState({Popups:[]});
    const route = IndependentCreator();

    useEffect(() => {
        popup.setOpenPopupListener(openPopupListener);
    }, [popupElements]);

    const pushPopup = (popupObj, props, onSelect, onClose) => {
        setPopupElements({
            Popups: [...popupElements.Popups, {Popup:popupObj, props:props, onSelect:onSelect, onClose:onClose}]
        });
    }

    const popPopup = () => {
        if(popupElements.Popups.length <= 0) return;

        let popups = popupElements.Popups;
        popups.splice(popups.length-1, 1);
        setPopupElements({
            Popups: [...popups]
        });
    }

    const openPopupListener = (pathOrComponent, props, onSelect=()=>{}, onClose=()=>{}) => {
        // openPopup 호출시 발생되는 이벤트

        // open popup action...
        let Popup = null;
        if(typeof pathOrComponent === 'string') {
            if(typeof route[pathOrComponent] === 'undefined') {
                throw Error(pathOrComponent + ' 경로의 컴포넌트를 찾을수 없습니다. 파일이 존재한다면 yarn screen 혹은 yarn start 하십시오.');
            }
            Popup = route[pathOrComponent];
        } else {
            Popup = pathOrComponent;
        }

        pushPopup(({...rest}) => { 
            return (
                <SafeAreaView style={{ flex: 1, marginTop: Platform.OS == "ios" ? Util.getStatusBarHeight() : 0, backgroundColor:'#ffffff', overflow:'hidden' }}>
                <Popup {...rest} />
                </SafeAreaView>
            )
        }, props, onSelect, onClose);
    }

    return (
        <PopupContext.Provider value={popup}>
            {children}
            {popupElements.Popups.map((popupObj, index) => {
                return (
                    <PopupProviderPopup key={index+''} popPopup={popPopup} popupObj={popupObj} />
                )
            })}
        </PopupContext.Provider>
    )
}
