import React, { useState, useEffect, useRef } from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
//import { Calendar, GetGroupingDate, ToMarkedDates } from '~/Components/UIControls/Calendar';
import { Calendar, CalendarList, Agenda } from 'react-native-calendars';
import _ from 'lodash';
import { useForm } from 'react-hook-form';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { useToast, confirm } from '~/Components/UIControls/Message';
import session from '~/Utils/session';
import fetchGet, { fetchPost, fetchPut, fetchDelete } from '~/Utils/fetch';
import { useAuth } from '~/Components/Hooks';
import { Util } from '~/Utils/utils';
import moment from 'moment';
import { ScrollView } from 'react-native-gesture-handler';
import Icon from '~/Components/UIControls/Icon';

const Screen = ({ navigation }) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState(null);
    const [calendar, setCalendar] = useState(null);
    const { auth, userinfo } = useAuth(navigation);
    const now = useRef(moment());
    const [current, setCurrent] = useState(now.current.format('YYYY-MM-DD'));

    const width = Util.getScreenWidth();

    useEffect(() => {
        getWorkState();
    }, []);

    const siteId = session.getSiteId();

    const getWorkState = () => {
        const sYear = now.current.year();
        const sMonth = now.current.month() + 1;
        setLoading(true);
        fetchGet(`/api/WorkResult/WorkStateCalendarSite?siteId=${siteId}&year=${sYear}&month=${sMonth}`)
            .then((data) => {
                setLoading(false);
                setData(data);

                console.log('data', data);
                let calendar = {};
                if (data.RequestResultList)
                    data.RequestResultList.map((item) => {
                        if (!calendar[item.Start]) calendar[item.Start] = {};
                        calendar[item.Start].title = item.Title;
                        calendar[item.Start].requestCount = item.RequestCount;
                        calendar[item.Start].confirmCount = item.ConfirmCount;
                    });
                if (data.WeekList)
                    data.WeekList.map((item) => {
                        if (!calendar[item.Start]) calendar[item.Start] = {};
                        calendar[item.Start].week = item.Title;
                    });
                setCalendar(calendar);
                setCurrent(now.current.format('YYYY-MM-DD'));
            })
            .catch((e) => {
                setLoading(false);
                Alert.alert('확인', e.message);
            });
    };

    const refreshList = () => {
        console.log('refreshList');
        getWorkState();
    };

    //console.log('calendar', calendar);
    console.log('current', current);

    return (
        <BottomTabBarLayout scroll={false}>
            <ScrollView>
                {calendar && (
                    <Calendar
                        onPressArrowLeft={() => {
                            now.current.subtract(1, 'month');
                            getWorkState();
                        }}
                        onPressArrowRight={() => {
                            now.current.add(1, 'month');
                            getWorkState();
                        }}
                        current={current}
                        monthFormat={'yyyy. MM'}
                        renderArrow={(direction) => {
                            if(direction == 'left') {
                                return (
                                    <View style={{
                                        flexDirection:'row',
                                        width: 80,
                                        height: 40,
                                        borderRadius: 6,
                                        borderWidth:1,
                                        borderColor:'#9aa3ac',
                                        alignItems:'center',
                                        justifyContent:'center'
                                    }}>
                                        <Icon iconFamily="AntDesign" iconName="left" size={20} color="#9aa3ac" />
                                        <Text>이전&nbsp;</Text>
                                    </View>
                                )
                            } else {
                                return (
                                    <View style={{
                                        flexDirection:'row',
                                        width: 80,
                                        height: 40,
                                        borderRadius: 6,
                                        borderWidth:1,
                                        borderColor:'#9aa3ac',
                                        alignItems:'center',
                                        justifyContent:'center'
                                    }}>
                                        <Text>&nbsp;다음</Text>
                                        <Icon iconFamily="AntDesign" iconName="right" size={20} color="#9aa3ac" />
                                    </View>
                                )
                            }
                        }}
                        displayLoadingIndicator={loading}
                        // Specify theme properties to override specific styles for calendar parts. Default = {}
                        theme={{}}
                        dayComponent={({ date, state, marking }) => {
                            let viewStyle = _.get(marking, 'customStyles.container');
                            const textStyle = _.get(marking, 'customStyles.text');
                            //console.log('date', date);
                            var dateObj = new Date(date.timestamp);
                            if (!data) {
                            }
                            if (state) {
                                //console.log('state', state);
                            }
                            const item = calendar[date.dateString] ?? {};
                            //console.log('calendar',calendar);
                            //console.log('dateStr',date.dateString);
                            //console.log('item',item);
                            return (
                                <>
                                    {dateObj.getDay() == 0 && item.week ? (
                                        <View
                                            style={{
                                                position: 'absolute',
                                                top: 35,
                                                width: width - 10,
                                                height: 35,
                                                backgroundColor: '#f8fcff',
                                                alignItems: 'flex-start',
                                                justifyContent: 'center',
                                                flexWrap: 'nowrap',
                                                alignSelf: 'stretch',
                                                paddingLeft: 10,
                                            }}
                                        >
                                            <Text style={{ color: '#707070', fontSize: 14 }}>{item.week}</Text>
                                        </View>
                                    ) : (
                                        <View style={{ height: 0 }}></View>
                                    )}
                                    <View style={{
                                        ...viewStyle, 
                                        width:'100%', 
                                        paddingHorizontal:3 ,
                                        borderTopWidth: 1,
                                        borderTopColor: '#dedede',
                                    }}>
                                        <Text
                                            style={{
                                                textAlign: 'center',
                                                color: state === 'disabled' ? 'gray' : 'black',
                                                height: 35,
                                                lineHeight: 35,
                                                ...textStyle,
                                            }}
                                        >
                                            {date.day}
                                        </Text>
                                        <View style={{ height: 35 }}></View>
                                        {(!!item.requestCount || !!item.confirmCount) && (
                                            <TouchableOpacity
                                                onPress={() => {
                                                    navigation.navigate('Form', {
                                                        action: Form.CREATE,
                                                        refreshList: refreshList,
                                                        siteId: session.getSiteId(),
                                                        auth: auth,
                                                        date: date.dateString,
                                                        id: 1,
                                                    });
                                                }}
                                            >
                                                <View
                                                    style={{
                                                        flexDirection: 'row',
                                                        borderRadius: 7,
                                                        width:'100%',
                                                        height: 30,
                                                        alignItems: 'center',
                                                        justifyContent: 'center',
                                                        borderWidth:1,
                                                        borderColor:'#0b83e6',
                                                    }}
                                                >
                                                    <Text>
                                                    {Util.get(item, 'requestCount', 0)}
                                                    </Text>
                                                    <Text>
                                                    /
                                                    </Text>
                                                    <Text style={{color:'#3b86ff'}}>
                                                    {Util.get(item, 'confirmCount', 0)}
                                                    </Text>
                                                </View>
                                            </TouchableOpacity>
                                        )}
                                    </View>
                                </>
                            );
                        }}
                        markingType={'custom'}
                    />
                )}

                <View style={{ flexDirection: 'row', alignItems:'center', justifyContent: 'flex-end', margin: 20 }}>
                    <View
                        style={{
                            width: 20,
                            height: 10,
                            borderRadius: 10,
                            alignItems: 'center',
                            backgroundColor: '#707070',
                            margin: 5,
                        }}
                    >
                    </View>
                    <Text style={{  }}>계획</Text>

                    <View
                        style={{
                            width: 20,
                            height: 10,
                            borderRadius: 10,
                            alignItems: 'center',
                            backgroundColor: '#0b83e6',
                            margin: 5,
                            marginLeft: 10,
                        }}
                    >
                    </View>
                    <Text style={{  }}>완료</Text>

                </View>

                {/*
                <View style={{ flexDirection: 'row', justifyContent: 'center', marginTop: 20 }}>
                    <View
                        style={{
                            width: 70,
                            borderRadius: 55,
                            paddingVertical: 7,
                            alignItems: 'center',
                            backgroundColor: '#007bff',
                            margin: 5,
                        }}
                    >
                        <Text style={{ color: '#fff' }}>계획</Text>
                    </View>
                    <View
                        style={{
                            width: 70,
                            borderRadius: 55,
                            paddingVertical: 7,
                            alignItems: 'center',
                            backgroundColor: '#28a745',
                            margin: 5,
                        }}
                    >
                        <Text style={{ color: '#fff' }}>완료</Text>
                    </View>
                </View>
                */}
            </ScrollView>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="캘린더" />,
    };
};

export default Screen;
