import React, { useEffect, useRef, useState, forwardRef, useImperativeHandle, useContext } from 'react';
import Styled from 'styled-components/native';
import LottieView from 'lottie-react-native';
import { getLottieColorFilters } from '~/Utils/lottie';
import { Dimensions, View, Platform } from 'react-native';
import { useGestureHandlerRef } from 'react-navigation-stack';
import Theme from '~/Themes';
import { Svgs } from '~/Generated/Svgs';
import { Util } from '~/Utils/utils';
import { useAuth } from '../Hooks';
import { TopMenu } from './TopMenu';
import fetchGet from '~/Utils/fetch';
import { useToast } from '../UIControls/Message';
import session from '~/Utils/session';
import { NavigationContext } from 'react-navigation';

const screenWidth = Dimensions.get('window').width;
const itemMaxHeight = 70;

const Container = Styled.View`
    flex: 1;
    flex-direction: column;
    background-color: #ffffff;
`;
const ScrollContentArea = Styled.ScrollView`
    flex: 1;
    background-color: #ffffff;
`;
const ContentArea = Styled.View`
    flex: 1;
    background-color: #ffffff;
`;
const TabBarContainer = Styled.View`
    height: 40px;
    border-color: #e9e9e9;
    border-top-width: 1px;
`;
const TabBarArea = Styled.ScrollView`
    background-color: white;
`;
const TabItem = Styled.TouchableOpacity`
    flex-direction: column;
    height: 40px;
    justify-content: center;
    align-items: center;
`;
const TabItemTitle = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    include-font-padding: false;
    font-size: 14;
    letter-spacing: -1.2;
    text-align: center;
    text-align-vertical: center;
    color: #abafb7;
    margin-top: 5px;
`;

const tabItems = [{
    name: '설비정보',
    icon: '/shortcut/bottom/facility',
    path: ''
}, {
    name: '경보정보',
    icon: '/shortcut/bottom/alarm',
    path: ''
}, {
    name: '구매신청',
    icon: '/shortcut/bottom/purchase',
    path: ''
}, {
    name: '작업현황',
    icon: '/shortcut/bottom/history',
    path: ''
}, {
    name: '사고민원',
    icon: '/shortcut/bottom/accident',
    path: ''
}];

let _shortcuts = [];
export const FetchShortcuts = async (showMessage, callback=()=>{}) => {
    try {
        await session.load();
        const result = await fetchGet(`api/app/MobileShortcut/BottomList?userId=${session.getUserInfo('UserId')}`);
        _shortcuts = [{
            Type: 1,
            SitemapId: 0,
            Icon: '/icons/gray/dashboard',
            Sitemap: {
                Name: '대시보드',
                Path: 'dashboard',
            },
        }, ...result];
        callback(_shortcuts);
    } catch(error) {
        showMessage(error.message);
    }
}

const BottomTabBarLayout = forwardRef(({children, scroll=false}, ref) => {
    const scrollView = useRef();
    const offset = useRef({x:0,y:0});
    const scrolling = useRef(false);
    const [shortcuts, setShortcuts] = useState(_shortcuts);
    const navigation = useContext(NavigationContext);
    const { showMessage } = useToast();

    const itemCount = shortcuts.length > 5 ? 5 : shortcuts.length;
    const itemWidth = Math.round(screenWidth / itemCount);
    const itemHeight = itemWidth > itemMaxHeight ? itemMaxHeight : itemWidth;
    
    const dock = () => {
        const remain = offset.current.x % itemWidth;
        const half = itemWidth / 2;
        if(remain < half) {
            // goto left -(remain)
            scrollView.current.scrollTo({x:offset.current.x-remain, y:0, animated:true});
        } else {
            // goto right +(itemWidth - remain)
            scrollView.current.scrollTo({x:offset.current.x+(itemWidth - remain), y:0, animated:true});
        }
    }

    useEffect(() => {
        if(shortcuts.length == 0) {
            FetchShortcuts(showMessage, (result) => {
                setShortcuts(result);
            });
        }
    }, []);

    useImperativeHandle(ref, () => ({
        fetchShortcuts: (callback=()=>{}) => {
            FetchShortcuts(showMessage, (result) => {
                setShortcuts(result);
                callback(result);
            });
        }
    }), [setShortcuts]);

    return (
        <Container>
            <TopMenu />
            {scroll ? (
                <ScrollContentArea>{children}</ScrollContentArea>
            ) : (
                <ContentArea>{children}</ContentArea>
            )}
            <TabBarContainer style={{height:itemHeight}}>
                <TabBarArea ref={(scroll) => { scrollView.current = scroll }} horizontal={true} 
                    showsVerticalScrollIndicator={false} 
                    showsHorizontalScrollIndicator={false}
                    onMomentumScrollBegin={() => {
                        scrolling.current = true;
                    }}
                    onMomentumScrollEnd={() => {
                        scrolling.current = false;
                        if(Platform.OS == 'android') {
                            dock();
                        }
                    }}
                    onScroll={(e) => {
                        const contentOffset = e.nativeEvent.contentOffset;
                        const pitch = Math.abs(offset.current.x - contentOffset.x);
                        offset.current = contentOffset;

                        if(scrolling.current) {
                            if(pitch <= 5) {
                                scrolling.current = false;
                                if(Platform.OS == 'android') {
                                    dock();
                                }
                            }
                        }
                    }}>
                    {
                        shortcuts.map((item, index) => {
                            const MenuIcon = Util.svg(item.Icon);

                            return (
                                <TabItem key={index} style={{minWidth:itemWidth, height:itemHeight}} onPress={() => { 
                                    if(item.Sitemap.Path) {
                                        if(item.Sitemap.Path == 'dashboard') {
                                            navigation.navigate('Dashboard');
                                        } else {
                                            Util.navigate(navigation, session.getMenu(item.Sitemap.Path));
                                        }
                                    }
                                }}>
                                    {MenuIcon ? (
                                        <MenuIcon width={itemHeight/3.7} height={itemHeight/3.7} />
                                    ): (
                                        <View style={{width:itemHeight/3.7, height:itemHeight/3.7}} />
                                    )}
                                    <TabItemTitle>{item.Sitemap.Name}</TabItemTitle>
                                </TabItem>
                            )
                        })
                    }
                </TabBarArea>
            </TabBarContainer>
        </Container>
    )
});

export default BottomTabBarLayout;