import React, { useState, useEffect, useRef, useCallback } from 'react';
import Styled from 'styled-components/native';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { Calendar, GetGroupingDate, ToMarkedDates } from '~/Components/UIControls/Calendar';
import Theme from '~/Themes';
import { WorkInfo } from '../Common/WorkInfo';
import { useAuth } from '~/Components/Hooks';
import { useToast } from '~/Components/UIControls/Message';
import fetchGet from '~/Utils/fetch';
import { View, Text, TouchableOpacity } from 'react-native';
import _ from 'lodash';
import { ListStyle } from '~/Components/Listing/Search';
import { Util } from '~/Utils/utils';
import session from '~/Utils/session';
import { NavigationActions, StackActions } from 'react-navigation';

const Screen = (props) => {
    const navigation = props.navigation;
    const [loading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    const [menus, setMenus] = useState({ process:{}, complete:{}, history:{} });
    const {auth, userinfo} = useAuth(navigation);
    const { showMessage } = useToast();

    useEffect(() => {
        (async () => {
            await session.load();
            await session.loadMenus();
            await session.loadSiteConfig();
            setMenus({
                process: {formName: 'WorkProcessForm', menu: session.getMenu('/Facility/WorkProcess')},
                complete: {formName: 'WorkCompleteForm', menu: session.getMenu('/Facility/WorkComplete')},
            });

            const curr = new Date();
            fetch(curr.getFullYear(), curr.getMonth()+1);
        })();
    }, []);

    const fetch = async (year, month) => {
        console.log('calender list fetch - ', year + '년 ' + month + '월');
        setLoading(true);
        try {
            const result = await fetchGet(`api/app/WorkResult/CalendarList?siteId=${userinfo.SiteId}&year=${year}&month=${month}&businessAuth=${auth.Business}`);
            setData(result);
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);
    }

    console.log('menus - ', menus);
    
    return (
        <BottomTabBarLayout scroll={false}>
            <Calendar displayLoadingIndicator={loading}
                dataTypes={[
                    {type:'정기점검', color:Theme.WorkTypeColor['정기점검']},
                    {type:'법정검사', color:Theme.WorkTypeColor['법정검사']},
                    {type:'수시점검', color:Theme.WorkTypeColor['수시점검']},
                    {type:'공사작업', color:Theme.WorkTypeColor['공사작업']},
                    {type:'법정교육', color:Theme.WorkTypeColor['법정교육']},
                ]} 
                onMonthChange={(month) => {
                    fetch(month.year, month.month);
                }}
                agendaRenderItem={({index, item, section, separators}) => {
                    return <AgendaItem navigation={navigation} menus={menus} index={index} item={item} section={section} />
                }}
                data={data} dataStartDateKey='StartDate' dataEndDateKey='EndDate' dataTypeKey='WorkTypeName' />
            <WorkInfo style={{ borderBottomWidth:0 }} />
        </BottomTabBarLayout>
    )
}

const AgendaContainer = Styled.View`
    background-color: #f5f5f5;
    padding-bottom: 10px;
    padding-left: 10px;
    padding-right: 10px;
    align-items: center;
    justify-content: center;
    min-height: 80px;
`;
const Agenda = Styled.View`
    background-color: white;
    padding: 20px;
    border-radius: 4;
    overflow:hidden;
    width: 100%;
    min-height: 50px;
`;
const AgendaEmptyText = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    include-font-padding: false;
    font-size:16;
    color: #9aa3ac;
`;
const AgendaEmptyItem = () => {
    return (
        <AgendaContainer style={{paddingTop:10}}>
            <AgendaEmptyText>작업일정 없음</AgendaEmptyText>
        </AgendaContainer>
    )
}
const WorkTypeShortName = {
    '정기점검': '정기',
    '법정검사': '법정',
    '법정교육': '법정',
    '수시점검': '수시',
    '공사작업': '공사',
};
const AgendaItem = ({navigation, menus, index, item, section, separators}) => {
    if(_.isEmpty(item)) {
        return <AgendaEmptyItem />
    }

    const color = Theme.WorkTypeColor[item.WorkTypeName];
    let menu = null;
    if(item.WorkProgressId == 4 || item.WorkProgressId == 7) {
        // to work process form
        menu = menus.process;
    } else if(item.WorkProgressId == 5) {
        // to work complete form
        menu = menus.complete;
    }

    return (
        <AgendaContainer style={[{paddingTop:index==0?10:0}]}>
            <Agenda>
                <TouchableOpacity style={[ListStyle.horizon]} onPress={() => {
                    if(menu != null) {
                        navigation.navigate(menu.formName, {
                            siteId: Util.get(item, 'SiteId'), 
                            workRequestId: Util.get(item, 'WorkRequestId'),
                            workProgressId: Util.get(item, 'WorkProgressId'),
                            auth: menu.menu.auth,
                            userinfo: session.getUserInfo(),
                            config: session.getSiteConfig(),
                        });
                    }
                }}>
                    <View style={[ListStyle.vertical,{flex:1}]}>
                        <Text style={[ListStyle.textGray]}>{Util.getDateString(item, "StartDate", ". ")} - {Util.getDateString(item, "EndDate", ". ")}</Text>
                        <Text style={[ListStyle.textMediumLarge]}>{item.Title}</Text>
                    </View>
                    <View style={[ListStyle.circleLarge, ListStyle.center, { paddingTop:0, borderWidth:0, backgroundColor:color }]}>
                        <Text style={[ListStyle.text], { color:'white' }}>{WorkTypeShortName[item.WorkTypeName]}</Text>
                    </View>
                </TouchableOpacity>
            </Agenda>
        </AgendaContainer>
    )
}

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="작업진행 달력" 
        /> 
    } 
};

export default Screen;