import React, { useState, Fragment, useContext, useRef, useEffect, useLayoutEffect } from 'react';
import Styled from 'styled-components/native';
import session from '~/Utils/session';
import { NavigationActions, NavigationContext } from 'react-navigation';
import { Util } from '~/Utils/utils';
import Theme from '~/Themes';

const MenuContainer = Styled.View`
`;
const MenuFirstLine = Styled.ScrollView`
    width: 100%;
    flex-direction: row;
`;
const MenuFirstItemFlex = Styled.View`
    border: 0px solid #e9e9e9;
    border-bottom-width: 1;
`;
const MenuFirstItem = Styled.TouchableOpacity`
    min-width: 94;
    height: 45;
    border: 0px solid #e9e9e9;
    border-bottom-width: 1;
    align-items: center;
    justify-content: center;
    padding-left: 10;
    padding-right: 10;
`;
const MenuFirstLabel = Styled.Text`
    font-family: ${Theme.Fonts.Medium};
    font-size: 16;
    line-height: 24;
    letter-spacing: -1.6;
    color: #707070;
`;
const MenuFirstItemActive = Styled(MenuFirstItem)`
    border: 0px solid #0b83e6;
    border-bottom-width: 3;
`;
const MenuFirstLabelActive = Styled(MenuFirstLabel)`
    color: #0b83e6;
`;
const MenuSecondLine = Styled.ScrollView`
    flex-direction: row;
    width: 100%;
    height: 45;
    border: 0px solid #e9e9e9;
    background-color: #f5f5f5;
    border-bottom-width: 1;
    padding-left: 3;
    padding-right: 3;
`;
const MenuSecondItem = Styled.TouchableOpacity`
    height: 100%;
    padding-left: 15;
    padding-right: 15;
    align-items: center;
    justify-content: center;
`;
const MenuSecondLabel = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    font-size: 16;
    line-height: 24;
    letter-spacing: -1.6;
    color: #707070;
`;
const MenuSecondLabelActive = Styled(MenuSecondLabel)`
    color: #0b83e6;
`;

export const TopMenu = ({main=true}) => {
    const navigation = useContext(NavigationContext);
    const sitemap = navigation.getParam('sitemap');
    const userinfo = navigation.getParam('userinfo');
    const config = navigation.getParam('config');
    if(!sitemap || !userinfo) return (<Fragment />);
    
    const [currentMenuId, setCurrentMenuId] = useState(sitemap.parentid);
    const menus = session.getMenus();
    let subMenu = {id:0, children:[]};
    if(main) {
        for(let menu of menus) {
            if(menu.id == currentMenuId) {
                subMenu = menu;
                break;
            }
        }
    }

    const navigate = (menu, parent) => {
        console.log('Navigate to', menu.path);
        const navigateAction = NavigationActions.navigate({
            routeName: menu.path,
            action: NavigationActions.navigate({ 
                routeName: 'Index', 
                params: {
                    auth: menu.auth,
                    userinfo: userinfo,
                    config: config,
                    sitemap: {
                        name: menu.name,
                        auth: menu.auth,
                        path: menu.path,
                        icon: menu.icon,
                        id: menu.id,
                        parentid: (parent == null ? 0 : parent.id),
                    },
                } 
            }),
        });
        navigation.dispatch(navigateAction);
    }

    const firstLine = useRef();
    const secondLine = useRef();
    const isSubMenuFind = useRef(false);
    isSubMenuFind.current = false;

    return (
        main ? (
            <MenuContainer>
                <MenuFirstLine horizontal={true} showsVerticalScrollIndicator={false} showsHorizontalScrollIndicator={false} ref={firstLine}>
                    {menus.map((menu, index) => {
                        const childMenu = menu.children.find((item, index) => {
                            return Util.get(menu, 'path', '').toLowerCase() == Util.get(item, 'path', '').toLowerCase();
                        });

                        return (
                            currentMenuId == menu.id ? (
                                <MenuFirstItemActive 
                                    key={index} 
                                    onPress={() => {
                                        setCurrentMenuId(menu.id);
                                        if(childMenu) {
                                            navigate(childMenu, menu);
                                        }
                                    }} 
                                    onLayout={(e) => {
                                        const layout = e.nativeEvent.layout;
                                        if(layout.x + layout.width > Util.getScreenWidth()) {
                                            const toValue = {x: layout.x, y:0, animated: true};
                                            firstLine.current.scrollTo(toValue);
                                        }
                                    }}>
                                    <MenuFirstLabelActive>{menu.name}</MenuFirstLabelActive>
                                </MenuFirstItemActive>
                            ) : (
                                <MenuFirstItem 
                                    key={index} 
                                    onPress={() => {
                                        setCurrentMenuId(menu.id);
                                        if(childMenu) {
                                            navigate(childMenu, menu);
                                        }
                                    }}>
                                    <MenuFirstLabel>{menu.name}</MenuFirstLabel>
                                </MenuFirstItem>
                            )
                        )
                    })}
                    <MenuFirstItemFlex/>
                </MenuFirstLine>
                <MenuSecondLine horizontal={true} showsVerticalScrollIndicator={false} showsHorizontalScrollIndicator={false} ref={secondLine}>
                    {subMenu.children.map((menu, index) => {
                        return (
                            sitemap.id == menu.id ? (
                                <MenuSecondItem key={index} 
                                    onPress={() => { navigate(menu, subMenu) }}
                                    onLayout={(e) => {
                                        const layout = e.nativeEvent.layout;
                                        if(layout.x + layout.width > Util.getScreenWidth()) {
                                            if(secondLine.current) {
                                                secondLine.current.scrollTo({x:layout.x, y:0, animated:true});
                                            }
                                        }
                                    }}>
                                    <MenuSecondLabelActive>{menu.name}</MenuSecondLabelActive>
                                    {(() => { isSubMenuFind.current = true; })()}
                                </MenuSecondItem>
                            ) : (
                                <MenuSecondItem key={index} onPress={() => { navigate(menu, subMenu) }}>
                                    <MenuSecondLabel>{menu.name}</MenuSecondLabel>
                                </MenuSecondItem>
                            )
                        )
                    })}
                </MenuSecondLine>
                {(() => {
                    if(!isSubMenuFind.current) {
                        if(secondLine.current) {
                            secondLine.current.scrollTo({x:0, y:0, animated:false});
                            secondLine.current.scrollTo({x:0, y:0, animated:false});
                        }
                    }
                })()}
            </MenuContainer>
        ) : (
            <Fragment />
        )
    );
}