import React, { useEffect, useState, useRef, useContext, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { refreshMenuAction } from '~/GlobalReducers/menu';
import Styled from 'styled-components/native';
import IconButton from '~/Components/UIControls/IconButton';
import { StyleSheet, Linking, View, Text } from 'react-native';
import Layout from '~/Components/Layouts/BottomTabBarLayout';
import { useToast } from '~/Components/UIControls/Message';
import Weather from './Weather';
import Shortcut from './Shortcut';
import { Util } from '~/Utils/utils';
import Theme from '~/Themes';
import Button from '~/Components/UIControls/Button';
import session from '~/Utils/session';
import EntitySelect from '~/Components/EntitySelect';
import { Config } from '~/Configuration';
import { SplashContext } from '~/Components/Splash';
import fetchGet, { fetchPost } from '~/Utils/fetch';
import { NotificationUtil } from '~/Utils/notificationUtil';
import Loading from '~/Components/UIControls/Loading';

const Container = Styled.View`
    flex: 1;
    background-color: #dadada;
`;
const TopGroup = Styled.View`
    flex-direction: row;
    height: 25%;
    margin-top: 3%;
`;
const TopLeft = Styled.View`
    width: 66%;
    margin-right: 3%;
    background-color: #00167a;
`;
const TopLeftInfo = Styled.TouchableOpacity`
    position: absolute;
    flex-direction: column;
    justify-content: center;
    left: 11%;
    top: 0;
    right: 0;
    bottom: 26%;
`;
const Title = Styled.Text`
    font-family: ${Theme.Fonts.Light};
    include-font-padding: false;
    font-size: 14;
    line-height: 19;
    letter-spacing:-1.05;
    color: white;
`;
const SiteName = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    include-font-padding: false;
    font-size: 24;
    line-height: 36;
    letter-spacing:-1.8;
    color: white;
`;
const TopRight = Styled.View`
    width: 31%;
    background-color: #7894ed;
`;
const TopRightWrap = Styled.View`
    position:absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 26%;
    align-items: center;
    justify-content: center;
`;
const TopRightInfo = Styled.View`
    flex-direction: column;
`;
const UserName = Styled.Text`
    font-family: ${Theme.Fonts.Light};
    include-font-padding: false;
    font-size: 15;
    line-height: 17;
    letter-spacing:-1.13;
    color: white;
`;
const Welcome = Styled.Text`
    font-family: ${Theme.Fonts.Light};
    include-font-padding: false;
    font-size: 15;
    line-height: 17;
    letter-spacing:-1.13;
    color: white;
`;
const FmsButton = Styled(Button)`
    padding:0;
    margin-top:10;
`;
const BottomGroup = Styled.View`
    flex-direction: column;
    position: absolute;
    left: 0px;
    top: 21%;
    right: 0px;
    bottom: -30px;
    background-color: white;
    border-radius: 30px;
    overflow: hidden;
`;
const WeatherContainer = Styled.View`
    width:100%;
    height:120px;
    border: 0px solid #e9e9e9;
    border-bottom-width: 1px;
    background-color: white;
`;
const SummaryContainer = Styled.View`
    width:100%;
    height:56px;
    border: 0px solid #e9e9e9;
    border-bottom-width: 1px;
    background-color: white;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding-horizontal: 15;
`;
const SummaryItem = Styled.View`
    height: 44px;
    padding-horizontal: 5px;
    justify-content: center;
    align-items: center;
`;
const SummaryCount = Styled.Text`
    font-family: ${Theme.Fonts.Medium};
    include-font-padding: false;
    font-size: 12;
    line-height: 17;
    letter-spacing:-0.6;
    color: #3284e9;
`;
const SummaryTitle = Styled.Text`
    font-family: ${Theme.Fonts.Medium};
    include-font-padding: false;
    font-size: 12;
    line-height: 17;
    letter-spacing:-0.6;
    color: black;
`;
const ShortcutContainer = Styled.View`
    flex: 1;
    background-color: white;
    padding-bottom:30px;
`;
const BuildingIcon = Util.svg('/dashboard/building');
const EarthIcon = Util.svg('/dashboard/earth');

const Screen = (props) => {
    const dispatch = useDispatch();
    const refreshMenu = useCallback((menu) => dispatch(refreshMenuAction(menu)), []);
    const navigation = props.navigation;
    const [userinfo, setUserInfo] = useState({});
    const [workState, setWorkState] = useState({});
    const siteRef = useRef();
    const splash = useContext(SplashContext);
    const { showMessage } = useToast();

    useEffect(() => {
        (async () => {
            await session.load();
            setUserInfo(session.getUserInfo());
            await fetchWorkState();
            splash.hide();
        })();
    }, []);

    const fetchWorkState = async () => {
        try {
            const data = await fetchGet('/api/Dashboard/ApporovalSummary', { siteId: userinfo.SiteId });
            setWorkState(data);
        } catch(error) {
            showMessage(error.message);
        }
    }

    const changeSite = async (item) => {
        userinfo.SiteId = item.value;
        userinfo.SiteName = item.label;
        userinfo.ApiSido = item.ApiSido;
        userinfo.ApiSigun = item.ApiSigun;
        session.setUserInfo(userinfo);
        session.setSiteId(userinfo.SiteId+'');
        setUserInfo({...userinfo});
        console.log('changed site : ', item);


        const clearAuth = (menus) => {
            for(let menu of menus) {
                if(typeof menu.auth !== 'undefined' && menu.auth) {
                    menu.auth.Update = false;
                    menu.auth.Delete = false;
                    menu.auth.Business = false;
                }
                if(typeof menu.children !== 'undefined') {
                    clearAuth(menu.children);
                }
            }
        }

        try{
            const menus = await fetchGet(`api/sitemap/menu/2?siteId=${session.getLoginSite().SiteId}&userGroupId=${userinfo.UserGroupId}`);

            if(session.getLoginSite().SiteId == userinfo.SiteId) {
                await session.saveMenus(menus);
            } else {
                clearAuth(menus);
                await session.saveMenus(menus);
            }

            refreshMenu({ refresh: Math.random() });
        } catch(error) {
            console.log(error);
            showMessage(error.message);
        }
    }

    return (
        <Layout navigation={navigation}>
            <Container>
                <TopGroup>
                    <TopLeft>
                        <BuildingIcon width={58} height={59} style={{position:'absolute', right:'10%', bottom:'26%'}} />
                        <TopLeftInfo 
                            onPress={() => { 
                                if(userinfo.IsAdmin) {
                                    siteRef.current.openSelect()
                                } else {
                                    Util.navigate(navigation, {
                                        path: '/Building/Site',
                                        auth: {
                                            Access: true,
                                            Update: true,
                                            Delete: true,
                                            Business: true,
                                        },
                                        name: '사옥정보',
                                        icon: '',
                                        id: 0,
                                        parentid: 0,
                                    }, null, {
                                        displaySiteInfo: true
                                    });
                                }
                            }}>
                            <Title>{userinfo.ApiSido} {userinfo.ApiSigun}</Title>
                            <SiteName>{userinfo.SiteName}</SiteName>
                            {userinfo.IsAdmin ? (
                                <EntitySelect entity="CmSite" id="SiteId" name="Name" fields="ApiSido,ApiSigun"
                                    useCheck={true} ref={siteRef} hidden={true}
                                    onChange={(item) => {
                                        changeSite(item);
                                    }} />
                            ) : null}
                        </TopLeftInfo>
                    </TopLeft>
                    <TopRight>
                        <EarthIcon width={71} height={55} style={{position:'absolute', top:0, right:0}} />
                        <TopRightWrap>
                            <TopRightInfo>
                                <UserName>{userinfo.Name}님</UserName>
                                <Welcome>환영합니다.</Welcome>
                                <FmsButton buttonStyle={{ 
                                    backgroundColor:'transparent', 
                                    borderWidth:1, 
                                    borderColor:'white',
                                    height: 30,
                                    width: 'auto',
                                    paddingLeft:10,
                                    paddingRight:10,
                                }} textStyle={{
                                    fontFamily: Theme.Fonts.Light,
                                    fontSize: 12,
                                    lineHeight: 17,
                                    letterSpacing: -0.9
                                }} onPress={() => {
                                    Linking.openURL(Config.WEB_URL);
                                }}>사옥웹 &nbsp;&nbsp;&gt;</FmsButton>
                            </TopRightInfo>
                        </TopRightWrap>
                    </TopRight>
                </TopGroup>
                <BottomGroup>
                    <WeatherContainer><Weather userinfo={userinfo} /></WeatherContainer>
                    <SummaryContainer>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.업무", '0')}</SummaryCount>
                            <SummaryTitle>업무</SummaryTitle>
                        </SummaryItem>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.자재입고", '0')}</SummaryCount>
                            <SummaryTitle>자재입고</SummaryTitle>
                        </SummaryItem>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.자재조정", '0')}</SummaryCount>
                            <SummaryTitle>자재조정</SummaryTitle>
                        </SummaryItem>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.공기구", '0')}</SummaryCount>
                            <SummaryTitle>공기구</SummaryTitle>
                        </SummaryItem>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.일지", '0')}</SummaryCount>
                            <SummaryTitle>일지</SummaryTitle>
                        </SummaryItem>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.보고서", '0')}</SummaryCount>
                            <SummaryTitle>보고서</SummaryTitle>
                        </SummaryItem>
                        <SummaryItem>
                            <SummaryCount>{Util.get(workState, "work.자재부족", '0')}</SummaryCount>
                            <SummaryTitle>자재부족</SummaryTitle>
                        </SummaryItem>
                    </SummaryContainer>
                    <ShortcutContainer><Shortcut navigation={navigation} /></ShortcutContainer>
                </BottomGroup>
            </Container>
        </Layout>
    );
};

export default Screen;