import React, { useState, Fragment, useCallback, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Styled from 'styled-components/native';
import { Platform, TouchableWithoutFeedback, Keyboard, TouchableOpacity, View, Modal } from 'react-native';
import { showAction } from '~/GlobalReducers/monthpicker';
import Button from './Button';
import { Util } from '~/Utils/utils';
import DownIcon from '~/Assets/Svgs/Selectbox/down.svg';
import Theme from '~/Themes';
import { usePrevious } from '../Hooks';
import MonthSelector from 'react-native-month-selector';
import 'moment/locale/ko';
import { getMomentsAsync } from 'expo-media-library';
import moment from 'moment';
import IconButton from './IconButton';

const ContainerStyle = `
    flex-direction: row;
    width: 100%;
    height: 40px;
    border: 1px solid #b9bac4;
    border-radius: 5px;
    align-items: center;
    padding-left: 19px;
    padding-right: 19px;
`;
const PickerLabel = Styled.Text`
    font-size: 15px;
    padding: 2px;
    padding-left: 0px;
    align-items: center;
    color: #43425d;
    flex: 1;
`;
const PickerDefaultLabel = Styled(PickerLabel)`
    color: #9aa3ac;
`;

const defaultOnChange = (newDate) => {};
export const MonthPicker = ({style={}, labelStyle={}, onChange=defaultOnChange, month=null, monthFormat="YYYY년 MM월", minimumDate=null, maximumDate=null, placeholder='', editable=true, useClear=false, hideDownIcon=false}) => {
    const [currentMonth, setCurrentMonth] = useState(month == null ? moment() : moment(month));
    const payload = useSelector(({GlobalMonthPicker}) => GlobalMonthPicker.picker);
    const dispatch = useDispatch();
    const show = useCallback((payload) => dispatch(showAction(payload)), []);
    const changeHandler = (momentValue) => {
        if(!!momentValue) {
            setCurrentMonth(momentValue);
            onChange(momentValue, momentValue.format(monthFormat));
        } else {
            setCurrentMonth('');
            onChange(moment(''), '');
        }
    }
    const clearValue = () => {
        changeHandler('');
    }
    const formatCurrentMonth = () => {
        if(currentMonth) {
            if(currentMonth.isValid()) {
                return currentMonth.format(monthFormat);
            } else {
                return '';
            }
        } else {
            return '';
        }
    }

    const Container = editable ? Styled(TouchableOpacity)`${ContainerStyle}` : Styled(View)`${ContainerStyle}`;
    const Label = currentMonth ? Styled(PickerLabel)`` : Styled(PickerDefaultLabel)``;
    const showParameter = {
        show:true, 
        minimumDate: minimumDate,
        maximumDate: maximumDate,
        month:currentMonth, 
        onChange:changeHandler
    };
    const borderStyle = editable ? { borderColor: Theme.COLORS.EDITABLE_BORDER } : { borderColor: Theme.COLORS.READONLY_BORDER };
    const backgroundStyle = editable ? { backgroundColor: Theme.COLORS.EDITABLE_BACKGROUND } : { backgroundColor: Theme.COLORS.READONLY_BACKGROUND };

    const prevEditable = usePrevious(editable);
    const prevMonth = usePrevious(month);

    useEffect(() => {
        if(typeof prevMonth !== 'undefined' && month != prevMonth) {
            setCurrentMonth(moment(month));
        }
        if(typeof prevEditable !== 'undefined' && editable != prevEditable) {
            onChange(moment(month));
        }
    }, [month, editable]);

    return (
        <Fragment>
            <Container style={[backgroundStyle, style, borderStyle]} onPress={() => { editable && show(showParameter); }}>
                <Label style={[labelStyle]} numberOfLines={1} ellipsizeMode="tail">{formatCurrentMonth()}</Label>
                {editable && !hideDownIcon && <DownIcon width={18} height={9} color="#b9bac4" />}
                {editable && useClear && <IconButton iconFamily="AntDesign" iconName="closecircle" color="#b9bac4" size={26} style={{marginLeft:10}} onPress={clearValue} />}
            </Container>
        </Fragment>
    );
}

export const MonthPickerProvider = () => {
    const payload = useSelector(({GlobalMonthPicker}) => GlobalMonthPicker.picker);
    const dispatch = useDispatch();
    const show = useCallback((payload) => dispatch(showAction(payload)), []);

    if(payload.show) {
        Keyboard.dismiss();
    }

    return (
        payload.show ? (
            <Modal 
                visible={payload.show} 
                transparent={true} 
                animationType="fade" 
                onRequestClose={() => { show({...payload.show, show:false}) }}
            >
                <View style={{position:'absolute', left:0, right:0, top:0, bottom:0, backgroundColor:'black', opacity:0.5}} />
                <View style={{width:'100%', height:'100%', flexDirection:'column', justifyContent:'flex-end'}}>
                    <View style={{flexDirection:'row', justifyContent:'flex-end', alignItems:'center', width:'100%', height:40, backgroundColor:'white'}}>
                        <Button 
                            buttonStyle={{width:80, height:32}} 
                            textStyle={{fontSize:17}} 
                            color="primary"
                            onPress={() => { show({...payload.show, show:false}) }}
                        >취소</Button>
                    </View>
                    <MonthSelector 
                        localeLanguage="ko"
                        nextText="다음"
                        prevText="이전"
                        selectedDate={payload.month==null?moment():moment(payload.month)}
                        minDate={payload.minimumDate==null?moment('2000-01-01'):moment(payload.minimumDate)}
                        maxDate={payload.maximumDate==null?moment():moment(payload.maximumDate)}
                        currentMonthTextStyle={{color:Theme.COLORS.PRIMARY}}
                        onMonthTapped={(month) => {
                            payload.onChange(month);
                            show({...payload.show, show:false});
                        }}
                    />
                </View>
            </Modal>
        ) : null
    )
}