import React, { Fragment, useState, useCallback, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { refreshMenuAction } from '~/GlobalReducers/menu';
import Styled from 'styled-components/native';
import { Block, Text, Button } from 'galio-framework';
import Theme from '~/Themes';
import UserSvg from '~/Assets/Svgs/user.svg';
import LockSvg from '~/Assets/Svgs/lock.svg';
import Icon from '~/Components/UIControls/Icon';
import { TouchableOpacity, View, UIManager, LayoutAnimation } from 'react-native';
import session from '~/Utils/session';
import { Svgs } from '~/Generated/Svgs';
import { NavigationActions } from 'react-navigation';
import { Util } from '~/Utils/utils';

const Container = Styled.SafeAreaView`
    flex: 1;
    background-color: #ffffff;
`;
const Header = Styled.TouchableOpacity`
    height: 77px;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding-left: 15px;
    padding-right: 10px;
    border: 0px solid #e9e9e9;
    border-bottom-width: 1px;
`;
const HeadUserBadge = Styled.View`
    width: 46px;
    height: 46px;
    align-items: center;
    justify-content: center;
    border-radius: 23px;
    background-color: #f5f5f5;
    overflow: hidden;
`;
const HeadUserInfo = Styled.View`
    flex: 1;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
`;
const HeadUserName = Styled.Text`
    color: black;
    font-family: ${Theme.Fonts.Medium};
    font-size: 18;
    line-height: 27;
    letter-spacing: -0.9;
`;
const HeadUserEmail = Styled.Text`
    color: #9aa3ac;
    font-family: ${Theme.Fonts.Regular};
    font-size: 12;
    line-height: 18;
`;
const HeadIconContainer = Styled.View`
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 46px;
    height: 25px;
    margin-top: 15px;
    alignSelf: flex-start;
`;

const Body = Styled.ScrollView`
    flex: 1;
`;

if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
}

const MenuItem = ({depth=1, leaf=false, active=false, root=false, name="", menuid="", icon="", path="", auth={}, onActive=()=>{}, onNavigate=(path)=>{}}) => {
    const MenuIcon = Util.svg(active ?  "/icons/white" : "/icons/color", icon);
    
    return (
        (() => {
            if(!leaf && depth == 1) {
                return (
                    active ? (
                        <TouchableOpacity onPress={() => {onActive()}} style={{ 
                            flexDirection:"row", backgroundColor:"#3a41d7", 
                            borderWidth:0, alignItems:"center", 
                            justifyContent:"space-between",
                            paddingLeft:15, paddingRight:15, height: 45
                        }}>
                            <View style={{width:30,height:18}}>
                                {MenuIcon ? <MenuIcon width={15} height={15} /> : null}
                            </View>
                            <Text style={{flex:1, fontFamily:Theme.Fonts.Medium, fontSize:16, lineHeight:24, letterSpacing:-0.8, color:"white"}} numberOfLines={1} ellipsizeMode="tail">{name}</Text>
                            <Icon iconFamily="Entypo" iconName="minus" fill="white" size={20} />
                        </TouchableOpacity>
                    ) : (
                        <TouchableOpacity onPress={() => {onActive()}} style={{ 
                            flexDirection:"row", backgroundColor:"white", 
                            borderWidth:0, borderBottomWidth:1, borderColor: "#e9e9e9",
                            alignItems:"center", justifyContent:"space-between",
                            paddingLeft:15, paddingRight:15, height: 45
                        }}>
                            <View style={{width:30,height:18}}>
                                {MenuIcon ? <MenuIcon width={15} height={15} fill="white" /> : null}
                            </View>
                            <Text style={{flex:1, fontFamily:Theme.Fonts.Medium, fontSize:16, lineHeight:24, letterSpacing:-0.8, color:"black"}} numberOfLines={1} ellipsizeMode="tail">{name}</Text>
                            <Icon iconFamily="Entypo" iconName="plus" color="#b9bac4" size={20} />
                        </TouchableOpacity>
                    )
                )
            } else if(leaf || depth >= 2 || root) {
                return (
                    root ? (
                        <TouchableOpacity onPress={() => {onNavigate()}} style={{ 
                            flexDirection:"row", backgroundColor:"white", 
                            borderWidth:0, borderBottomWidth:1, borderColor: "#e9e9e9",
                            alignItems:"center", justifyContent:"space-between",
                            paddingLeft:15, paddingRight:15, height: 45
                        }}>
                            <View style={{width:30,height:18}}>
                                {MenuIcon ? <MenuIcon width={15} height={15} fill="white" /> : null}
                            </View>
                            <Text style={{flex:1, fontFamily:Theme.Fonts.Medium, fontSize:16, lineHeight:24, letterSpacing:-0.8, color:"black"}} numberOfLines={1} ellipsizeMode="tail">{name}</Text>
                            <Icon iconFamily="Ionicons" iconName="ios-arrow-forward" color="#9aa3ac" size={20} style={{marginRight:5}} />
                        </TouchableOpacity>
                    ) : (
                        <TouchableOpacity onPress={() => {if(path) { onNavigate(path) }}} style={{
                            flexDirection:"row", backgroundColor:"#f5f5f5", 
                            borderWidth:0, borderBottomWidth:1, borderColor: "#e9e9e9",
                            alignItems:"center", justifyContent:"space-between",
                            paddingLeft:22, paddingRight:21, height: 45
                        }}>
                            <Text style={{flex:1, fontFamily:Theme.Fonts.Regular, fontSize:16, lineHeight:24, letterSpacing:-0.8, color:"#707070"}} numberOfLines={1} ellipsizeMode="tail">{name}</Text>
                            <Icon iconFamily="Ionicons" iconName="ios-arrow-forward" color="#9aa3ac" size={20} />
                        </TouchableOpacity>
                    )
                )
            } else {
                return <View />
            }
        })()
    )
}

const MenuElement = ({items, parent=null, depth = 1, navigation}) => {

    return (
        <View>
        {parent == null && (
            <MenuItem depth={1} leaf={true} root={true} name="대시보드" icon="dashboard"
                onNavigate={() => {
                    navigation.navigate('Dashboard');
                }} />
        )}
        {items.map((menu, index) => {
            const hasChildren = typeof menu.children != 'undefined' && Array.isArray(menu.children) && menu.children.length > 0 ? true : false;
            const [active, setActive] = useState(false);

            return (
                <Fragment key={index}>
                    <MenuItem depth={depth} leaf={!hasChildren} active={active}
                        name={menu.name} icon={menu.icon} menuid={menu.id} 
                        auth={menu.auth} path={menu.path}
                        onActive={() => {
                            LayoutAnimation.configureNext(
                                LayoutAnimation.create(150, LayoutAnimation.Types.easeInEaseOut, LayoutAnimation.Properties.opacity)
                            );
                            setActive(!active);
                        }}
                        onNavigate={(path) => {
                            console.log(path);
                            Util.navigate(navigation, menu, (parent == null ? 0 : parent.id));
                        }} />
                    { hasChildren && active && (
                        <MenuElement items={menu.children} parent={menu} depth={depth+1} navigation={navigation} />
                    )}
                </Fragment>
            )
        })}
        </View>
    )
};

const Drawer = (props) => {
    const globalMenu = useSelector(({ GlobalMenu }) => GlobalMenu.menu);
    const navigation = props.navigation;
    const [menus, setMenus] = useState([]);

    useEffect(() => {
        loadMenus();
    }, [globalMenu]);

    const loadMenus = async () => {
        const list = await session.loadMenus(true);
        await session.load();
        setMenus(list);
    }

    return (
        <Container forceInset={{ top: 'always', horizontal: 'never' }}>
            <Header onPress={() => {
            }}>
                <HeadUserBadge>
                    <UserSvg width={18} height={19} color="black" />
                </HeadUserBadge>
                <HeadUserInfo>
                    <HeadUserName>{session.getUserInfo("Name")}님</HeadUserName>
                    <HeadUserEmail>{session.getUserInfo("UserId")}</HeadUserEmail>
                </HeadUserInfo>
                <HeadIconContainer>
                    <TouchableOpacity onPress={() => { session.logout(navigation) }}>
                        <LockSvg width={15} height={17} color="black" />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => { navigation.closeDrawer() }}>
                        <Icon iconFamily="MaterialCommunityIcons" iconName="close" color="black" size={25} />
                    </TouchableOpacity>
                </HeadIconContainer>
            </Header>
            
            <Body>
                {menus != null && Array.isArray(menus) && (
                    <MenuElement items={menus} depth={1} navigation={navigation} />
                )}
            </Body>
        </Container>
    )
};

export default Drawer;