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 moment from 'moment';

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

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

    const siteId = session.getSiteId();

    const getHoliday = () => {
        const sYear = now.current.year();
        const sMonth = now.current.month() + 1;
        setLoading(true);
        fetchGet(`/api/Holiday/ListCalendar?siteId=${siteId}&year=${sYear}&month=${sMonth}`)
            .then((data) => {
                setLoading(false);
                console.log('data', data);

                let newholiday = {};
                data.HolidayList.forEach((item) => {
                    if (item.IsLunar) {
                        newholiday[item.Date] = {
                            type: item.Type,
                            date: item.Date,
                            id: item.Id,
                            isLunar: item.IsLunar,
                            title: item.Title,
                        };
                    } else {
                        newholiday[item.Date] = {
                            type: item.Type,
                            date: item.Date,
                            id: item.Id,
                            isLunar: item.IsLunar,
                            title: item.Title,
                        };
                    }
                });

                setHolidays(newholiday);
                setData(data);
                setCurrent(now.current.format('YYYY-MM-DD'));
            })
            .catch((e) => {
                setLoading(false);
                Alert.alert('확인', e.message);
            });
    };

    if (holidays) {
        //console.log('holidays', holidays);
    }

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

    return (
        <BottomTabBarLayout scroll={false}>
            <Button
                title={'Info'}
                onPress={() => {
                    navigation.navigate('WeekendForm', {
                        action: Form.EDIT,
                        refreshList: refreshList,
                        siteId: session.getSiteId(),
                        auth: auth,
                    });
                }}
            >
                주말 설정
            </Button>
            {data && (
                <Calendar
                    onPressArrowLeft={() => {
                        now.current.subtract(1, 'month');
                        getHoliday();
                    }}
                    onPressArrowRight={() => {
                        now.current.add(1, 'month');
                        getHoliday();
                    }}
                    current={current}
                    displayLoadingIndicator={loading}
                    // Specify theme properties to override specific styles for calendar parts. Default = {}
                    theme={{}}
                    onDayPress={(day) => {
                        console.log('selected day', day);
                    }}
                    dayComponent={({ date, state, marking }) => {
                        let viewStyle = _.get(marking, 'customStyles.container');
                        const textStyle = _.get(marking, 'customStyles.text');
                        var dateObj = new Date(date.timestamp);
                        if (data) {
                            if (dateObj.getDay() == 6 && data.Saturday === true) {
                                viewStyle = { ...viewStyle, backgroundColor: '#fcc' };
                            }
                            if (dateObj.getDay() == 0 && data.Sunday === true) {
                                viewStyle = { ...viewStyle, backgroundColor: '#fcc' };
                            }
                        }
                        const holiday = holidays[date.dateString];
                        if (holiday) {
                            //console.log('holiday', holiday);
                        }
                        if (holiday) {
                            if (holiday.type == 'C') {
                                viewStyle = { ...viewStyle, backgroundColor: '#fd9' };
                            } else {
                                viewStyle = { ...viewStyle, backgroundColor: '#9cf' };
                            }
                        }
                        if (state) {
                            //console.log('state', state);
                        }
                        let dateStr = date.dateString.replace(/-/g, '');
                        if (holiday && holiday.type == 'H') {
                            dateStr = [dateObj.getMonth() + 1, dateObj.getDate()].join('-');
                        }
                        return (
                            <TouchableOpacity
                                onPress={() => {
                                    if (holiday) {
                                        navigation.navigate('Form', {
                                            action: Form.VIEW,
                                            refreshList: refreshList,
                                            siteId: session.getSiteId(),
                                            type: holiday.type,
                                            date: dateStr,
                                            auth: auth,
                                            userinfo: userinfo,
                                        });
                                    } else {
                                        navigation.navigate('Form', {
                                            action: Form.CREATE,
                                            refreshList: refreshList,
                                            siteId: session.getSiteId(),
                                            auth: auth,
                                            date: date.dateString,
                                        });
                                    }
                                }}
                            >
                                <View style={{ width: 30, height: 30, borderRadius: 5, padding: 5, ...viewStyle }}>
                                    <Text
                                        style={{
                                            textAlign: 'center',
                                            color: state === 'disabled' ? 'gray' : 'black',
                                            ...textStyle,
                                        }}
                                    >
                                        {date.day}
                                    </Text>
                                </View>
                            </TouchableOpacity>
                        );
                    }}
                    markingType={'custom'}
                />
            )}
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({ navigation }) => {
    return {
        header: () => <Header navigation={navigation} title="휴일관리" />,
    };
};

export default Screen;
