import React from 'react';
import { StyleSheet, View, Text, TextInput, Button, StatusBar, Picker, Alert, Image, Platform } from 'react-native';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import Axios from 'axios';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import { BASE_URL_GET_ENUM, BASE_URL_REGISTER } from '../model/Base_Model';
import i18n from 'i18n-js';
import Spinner from 'react-native-loading-spinner-overlay';
// import { connect } from 'react-redux';
import RNPickerSelect from 'react-native-picker-select';
import MyStatusBar from './MyStatusBar';
import requestParams from '../helper/requestParams';


var date = [
    i18n.t('pilih'), "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21",
    "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
]
var month = [
    i18n.t('pilih'), "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September",
    "Oktober", "November", "Desember"
]

var year = [
    i18n.t('pilih'), "1960", "1961", "1962", "1963", "1964", "1965", "1966", "1967", "1968", "1969", "1970", "1971",
    "1972", "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987",
    "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004",
    "2005", "2006", "2007"
]


class NewRegister extends React.Component {
    constructor(props) {
        super(props);
        this.state = ({
            dateAndroid : [
                i18n.t('pilih'), "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21",
                "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"
            ],
            monthAndroid : [
                i18n.t('pilih'), "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September",
                "Oktober", "November", "Desember"
            ],
            yearAndroid : [
                i18n.t('pilih'), "1960", "1961", "1962", "1963", "1964", "1965", "1966", "1967", "1968", "1969", "1970", "1971",
                "1972", "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987",
                "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004",
                "2005", "2006", "2007"
            ],
            caretHidden: true,
            email: "",
            password: "",
            full_name: "",
            gender: "",
            confirm_pass: "",
            date: [],
            month: [],
            year: [],
            dob_year: "",
            dob_month: "",
            dob_day: "",
            list_gender: { "0": i18n.t('other'), "1": i18n.t('male'), "2": i18n.t('female') },
            gender_list: [],
            list_domicilie: [],
            list_profesion: [],
            list_dob: [],
            selected_item: [],
            language: 'id',
            spinner: false,
        })
    }

    componentDidMount() {
        this.load_data();
        // console.log("INI YA : " + this.props.BASE_URL)

        let date_list = []
        for (let i = 1; i <= 31; i++) {
            date_list.push({ label: String(i), value: i });
        }
        let month_list = []
        for (let i = 1; i <= 12; i++) {
            const month_name = month[i];
            month_list.push({ label: month_name, value: i });
        }
        let year_list = []
        let current_year = new Date().getFullYear();
        let start_year = current_year - 65;
        let end_year = current_year - 13;
        for (let i = start_year; i <= end_year; i++) {
            year_list.push({ label: String(i), value: i });
        }
        this.setState({
            date: date_list,
            month: month_list,
            year: year_list
        })
    }

    load_data() {
        return Axios.get(this.props.BASE_URL + 'crm/v2/auth/register_get_enum').then(res => {
            // console.log('ini res enum nya : ' + JSON.stringify(res));
            const data_enum = res.data;
            const list_gender = data_enum.gender
            const list_profesion = data_enum.profession
            const list_domicilie = data_enum.domicile
            let gender_list = []
            for (const key in list_gender) {
                if (list_gender.hasOwnProperty(key)) {
                    const row = list_gender[key];
                    gender_list.push({ label: row, value: key })
                }
            }
            this.setState({
                // list_gender: list_gender,
                list_profesion: list_profesion,
                list_domicilie: list_domicilie,
                gender_list: gender_list,
            })
            // console.log(this.state.list_gender)
        })
    }

    validate() {
        if (this.state.email === "") {
            Alert.alert(
                '',
                i18n.t('alertEmailMustFill')
                ,
            )
        } else if (this.state.password === "") {
            Alert.alert(
                '',
                i18n.t('alertPasswordMustFill')
                ,
            )
        } else if (this.state.confirm_pass === "") {
            Alert.alert(
                '',
                i18n.t('alertConfirmPassMustFill')
                ,
            )
        } else if (this.state.confirm_pass !== this.state.password) {
            Alert.alert(
                '',
                i18n.t('alertPasswordMustBeSame')
                ,
            )
        }
        else if (this.state.full_name === "") {
            Alert.alert(
                '',
                i18n.t('alertNameMustFill')
                ,
            )
        } else if (this.state.dob_day === "") {
            Alert.alert(
                '',
                i18n.t('alertDOBMustFill')
                ,
            )
        }
        else if (this.state.dob_day === "Pilih") {
            Alert.alert(
                '',
                i18n.t('alertDOBMustFill')
                ,
            )
        } else if (this.state.dob_month === "") {
            Alert.alert(
                '',
                i18n.t('alertDOBMustFill')
                ,
            )
        } else if (this.state.dob_month === "Pilih") {
            Alert.alert(
                '',
                i18n.t('alertDOBMustFill')
                ,
            )
        } else if (this.state.dob_year === "") {
            Alert.alert(
                '',
                i18n.t('alertDOBMustFill')
                ,
            )
        } else if (this.state.dob_year === "Pilih") {
            Alert.alert(
                '',
                i18n.t('alertDOBMustFill')
                ,
            )
        } else if (this.state.gender === "") {
            Alert.alert(
                '',
                i18n.t('alertGenderMustFill')
                ,
            )
        } else if (this.state.gender === "Pilih") {
            Alert.alert(
                '',
                i18n.t('alertGenderMustFill')
                ,
            )
        } else {
            this.handleReg()
        }
    }

    handleReg() {
        this.setState({
            spinner: true,
        })

        let params = Object.assign(requestParams, {
            "email": this.state.email,
            "password": this.state.password,
            "name": this.state.full_name,
            "gender": this.state.gender,
            "dob_year": this.state.dob_year.toString(),
            "dob_month": this.state.dob_month.toString(),
            "dob_day": this.state.dob_day.toString(),

        })


        // console.log(parameter);
        Axios.post(this.props.BASE_URL + 'crm/v2/auth/register', params).then(res => {
            // console.log(res);
            let registerProps = {
                email: this.state.email,
                full_name: this.state.full_name,
                gender: this.state.gender,
                dob_day: this.state.dob_day,
                dob_month: this.state.dob_month,
                dob_year: this.state.dob_year,
                password: this.state.password,
                registration_id: res.data.id
            }
            let prosesProps = {
                proses: 'Register'
            }
            let pageProps = {
                pageEmailConfirmation: true
            }
            let emailConfirmProps = {
                isEmailverif: false
            }
            this.props.setPage(pageProps)
            this.props.setEmailConfirm(emailConfirmProps)
            this.props.setProses(prosesProps);
            this.props.setRegistration(registerProps);
            Alert.alert(
                '',
                i18n.t('alertCheckEmail'),
                [
                    {
                        text: 'OK', onPress: () => {
                            this.setState({
                                spinner: false,
                            })

                            this.props.navigation.navigate('Email Confirmation')
                        }

                    }
                ],
                { cancelable: false }
            );
        }).catch(error => {

            // console.log(JSON.stringify(error.response));
            let response = error.response.data;
            Alert.alert(
                '',
                response.msg,
                [
                    {
                        text: 'OK', onPress: () => this.setState({
                            spinner: false,
                        })
                    }
                ]
            );
        })

    }
    render() {
        return (
            <View style={styles.container}>
                <MyStatusBar />
                <ScrollView>
                    <Spinner
                        visible={this.state.spinner}
                        textContent={'Loading...'}
                        textStyle={styles.spinnerTextStyle}
                    />
                    <View style={styles.body}>

                        <View style={styles.itemsRow}>
                            <View style={styles.items1}>
                                <Text style={{ textAlign: 'center', color: '#CFB368', fontWeight: 'bold' }}>{i18n.t('email')}</Text>
                            </View>
                            <View style={styles.items2}>
                                <TextInput
                                    caretHidden={this.state.caretHidden}
                                    onFocus={() => this.setState({ caretHidden: false })}
                                    style={styles.textInput}
                                    onChangeText={(email) => this.setState({ email })}
                                    value={this.state.email}
                                    keyboardType='email-address'
                                    autoCapitalize="none"
                                    placeholder='Example@gmail.com'
                                    placeholderTextColor='gray'
                                    textAlign='center'
                                // autoCompleteType="email"
                                />
                            </View>
                        </View>
                        <View style={styles.itemsRow}>
                            <View style={styles.items1}>
                                {/* <Text>{i18n.t('password')}</Text> */}
                                <Text style={{ textAlign: 'center', color: '#CFB368', fontWeight: 'bold' }}>{i18n.t('password')}</Text>
                            </View>
                            <View style={styles.items2}>
                                <TextInput
                                    caretHidden={this.state.caretHidden}
                                    onFocus={() => this.setState({ caretHidden: false })}
                                    style={styles.textInput}
                                    onChangeText={(password) => this.setState({ password })}
                                    value={this.state.password}
                                    secureTextEntry={true}
                                    placeholder='******'
                                    placeholderTextColor='gray'
                                    textAlign='center'
                                />
                            </View>
                        </View>
                        <View style={styles.itemsRow}>
                            <View style={styles.items1}>
                                {/* <Text>{i18n.t('password2')}</Text> */}
                                <Text style={{ textAlign: 'center', color: '#CFB368', fontWeight: 'bold' }}> {i18n.t('Confirmpassword')}</Text>
                            </View>
                            <View style={styles.items2}>
                                <TextInput
                                    style={styles.textInput}
                                    caretHidden={this.state.caretHidden}
                                    onFocus={() => this.setState({ caretHidden: false })}
                                    onChangeText={(confirm_pass) => this.setState({ confirm_pass })}
                                    value={this.state.confirm_pass}
                                    secureTextEntry={true}
                                    placeholder='******'
                                    placeholderTextColor='gray'
                                    textAlign='center'
                                />
                            </View>
                        </View>
                        <View style={styles.itemsRow}>
                            <View style={styles.items1}>
                                {/* <Text>{i18n.t('name')}</Text> */}
                                <Text style={{ textAlign: 'center', color: '#CFB368', fontWeight: 'bold' }}>{i18n.t('Name')}</Text>
                            </View>
                            <View style={styles.items2}>
                                <TextInput
                                    style={styles.textInput}
                                    caretHidden={this.state.caretHidden}
                                    onFocus={() => this.setState({ caretHidden: false })}
                                    onChangeText={(full_name) => this.setState({ full_name })}
                                    value={this.state.full_name}
                                    placeholder='Example'
                                    placeholderTextColor='gray'
                                    textAlign='center'
                                />
                            </View>
                        </View>
                        <View style={styles.itemsRow}>
                            <View style={styles.items1}>
                                <Text style={{ textAlign: 'center', color: '#CFB368', fontWeight: 'bold' }}>{i18n.t('dob')}</Text>
                            </View>
                            {Platform.OS === 'ios' ? (
                                <View style={styles.itemPicker}>

                                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', marginLeft: 10 }}>
                                        <RNPickerSelect onValueChange={(value) => this.setState({ dob_day: value })}
                                            items={this.state.date}
                                            placeholder={{ label: '-- Select --' }}
                                            style={{ inputIOSContainer: { paddingVertical: 10, alignItems: 'center' } }}
                                        />
                                    </View>
                                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                                        <RNPickerSelect onValueChange={(value) => this.setState({ dob_month: value })}
                                            items={this.state.month}
                                            placeholder={{ label: '-- Select --' }}
                                            style={{ inputIOSContainer: { paddingVertical: 10, alignItems: 'center' } }}
                                        />
                                    </View>
                                    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', marginRight: 10 }}>
                                        <RNPickerSelect onValueChange={(value) => this.setState({ dob_year: value })}
                                            items={this.state.year}
                                            placeholder={{ label: '-- Select --' }}
                                            style={{ inputIOSContainer: { paddingVertical: 10, alignItems: 'center' } }}
                                        />
                                    </View>
                                </View>
                            ) : (
                                    <View style={styles.itemPicker}>

                                        <View style={{ height: 35, flex: 1, alignItems: 'center', }}>
                                            <Picker
                                                mode="dropdown"
                                                selectedValue={this.state.dob_day}
                                                style={{ height: 35, width: 90 }}
                                                onValueChange={(itemValue, itemIndex) => this.setState({ dob_day: itemValue })}>
                                                {this.state.dateAndroid.map((itemValue, itemIndex) => {
                                                    return (<Picker.Item label={itemValue} value={itemValue} key={itemIndex} />)
                                                })}

                                            </Picker>
                                        </View>
                                        <View style={{ height: 35, flex: 1, alignItems: 'center' }}>
                                            <Picker
                                                mode="dropdown"
                                                selectedValue={this.state.dob_month}
                                                style={{ height: 35, width: 105 }}
                                                onValueChange={(itemValue, itemIndex) =>
                                                    this.setState({ dob_month: itemValue })
                                                }>
                                                {this.state.monthAndroid.map((itemValue, itemIndex) => {
                                                    return (<Picker.Item label={itemValue} value={itemIndex} key={itemIndex} />)
                                                })}
                                            </Picker>
                                        </View>
                                        <View style={{ height: 35, flex: 1, alignItems: 'center' }}>
                                            <Picker
                                                mode="dropdown"
                                                selectedValue={this.state.dob_year}
                                                style={{ height: 35, width: 105 }}
                                                onValueChange={(itemValue, itemIndex) =>
                                                    this.setState({ dob_year: itemValue })
                                                }>
                                                {this.state.yearAndroid.map((itemValue, itemIndex) => {
                                                    return (<Picker.Item label={itemValue} value={itemValue} key={itemIndex} />)
                                                })}
                                            </Picker>
                                        </View>
                                    </View>

                                )}
                        </View>


                        <View style={styles.itemsRow}>
                            <View style={styles.items1}>
                                <Text style={{ textAlign: 'center', color: '#CFB368', fontWeight: 'bold' }}>{i18n.t('gender')}</Text>
                            </View>
                            {Platform.OS === 'ios' ? (
                                <View style={styles.pickerGender}>
                                    <RNPickerSelect onValueChange={(value) => this.setState({ gender: value })}
                                        items={this.state.gender_list}
                                        placeholder={{ label: '-- Select --' }}
                                        style={{ inputIOSContainer: { paddingVertical: 10, alignItems: 'center' } }}
                                    />
                                </View>
                            ) : (
                                    <View style={styles.pickerGender}>
                                        <Picker selectedValue={this.state.gender}
                                            onValueChange={(itemValue, itemIndex) => this.setState({ gender: itemValue })}>
                                            <Picker.Item label={i18n.t('pilih')} value='' />
                                            {
                                                Object.entries(this.state.list_gender).map((item, key) =>
                                                    <Picker.Item label={item[1]} key={key} value={item[0]}>
                                                    </Picker.Item>
                                                )
                                            }
                                        </Picker>
                                    </View>
                                )}
                        </View>
                        <TouchableOpacity onPress={() => this.validate()}>
                            <View style={styles.button}>
                                <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 22 }}>{i18n.t('register')}</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this.props.navigation.navigate('Login')}>
                            <View style={styles.signin}>
                                <Text style={{ color: '#CFB368' }}>{i18n.t('login')}</Text>
                            </View>
                        </TouchableOpacity>
                        <View style={{ flex: 1 }}>
                            <Image source={require('../assets/images/file-register.png')} resizeMethod='resize' resizeMode='contain' style={{ height: 300, width: '100%' }}></Image>
                        </View>
                    </View>
                </ScrollView>
            </View>
        )
    }
}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    header: {
        flex: 0.1,
        backgroundColor: '#CFB368',
        justifyContent: 'center',
        alignItems: 'center'
    },
    body: {
        flex: 0.8,
        flexDirection: 'column',
    },
    itemsRow: {
        // flexDirection: 'row',
        marginTop: 25,
    },
    items1: {
        marginBottom: 10
    },
    items2: {
        flex: 1,
        height: 35,
        marginHorizontal: 15,
        justifyContent: 'center',
        alignItems: 'stretch',
    },
    items3: {
        flex: 1,
        height: 35,
        marginHorizontal: 15,
        justifyContent: 'center',
        alignItems: 'stretch',
        borderWidth: 1
    },
    itemPicker: {
        flexDirection: 'row',
        flex: 1,
        marginLeft: 44,
        marginRight: 44,
        borderColor: 'gray',
        borderWidth: 1,
        borderRadius: 10,
        height: 40,
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    titleText: {
        margin: 15,
        fontSize: 26,
        fontWeight: 'bold',
        color: 'white',
        fontFamily: 'Gotham-Black'
    },
    textInput: {
        height: 40,
        borderColor: 'gray',
        borderWidth: 1,
        padding: 10,
        margin: 30,
        borderRadius: 10
    },
    pickerGender: {
        height: 40,
        borderColor: 'gray',
        borderWidth: 1,
        borderRadius: 10,
        // padding: 10,
        marginLeft: 44,
        marginRight: 44,
        // alignItems: 'stretch',
        justifyContent: 'center'
    },
    button: {
        backgroundColor: '#CFB368',
        marginTop: 25,
        marginHorizontal: 100,
        borderRadius: 15,
        paddingVertical: 5,
        alignItems: 'center',
        justifyContent: 'center'
    },
    signin: {
        marginTop: 25,
        alignItems: 'center',
    },
    textSignIn: {
        color: 'red'
    }
})

const mapStateToProps = (state) => {
    return {
        language: state.language,
        BASE_URL: state.BASE_URL,
    }
}

const mapDispatchToProps = (dispacth) => {
    return {
        setRegistration: (registerProps) => dispacth({
            type: ActionType.SET_REGISTRATION,
            data: {

                full_name: registerProps.full_name,
                gender: registerProps.gender,
                dob_day: registerProps.dob_day,
                dob_month: registerProps.dob_month,
                dob_year: registerProps.dob_year,
                email: registerProps.email,
                password: registerProps.email,
                registration_id: registerProps.registration_id
            }
        }),
        setProses: (prosesProps) => dispacth({
            type: ActionType.SET_PROSES,
            data: {
                proses: prosesProps.proses,
            }
        }),
        setPage: (pageProps) => dispacth({
            type: ActionType.SET_PAGE,
            data: {
                pageEmailConfirmation: pageProps.pageEmailConfirmation
            }
        }),
        setEmailConfirm: (emailConfirmProps) => dispacth({
            type: ActionType.SET_EMAIL_VERIFICATION,
            data: {
                isEmailverif: emailConfirmProps.isEmailverif,
            }
        }),
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(NewRegister);