import React from 'react';
import { StyleSheet, View, Text, TextInput, Button, StatusBar, Picker, Alert } 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';


var date = [
    "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 = [
    "Pilih", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September",
    "Oktober", "November", "Desember"
]

var year = [
    "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 = ({
            email: "",
            password: "",
            full_name: "",
            gender: "",
            confirm_pass: "",
            date: [],
            month: [],
            year: [],
            dob_year: "",
            dob_month: "",
            dob_day: "",
            list_gender: [],
            list_domicilie: [],
            list_profesion: [],
            list_dob: [],
            selected_item: [],
            language: 'id',
            spinner: false,
        })
    }

    componentDidMount() {
        this.load_data();
    }

    load_data() {
        return Axios.get(BASE_URL_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
            this.setState({
                list_gender: list_gender,
                list_profesion: list_profesion,
                list_domicilie: list_domicilie,
            })
        })
    }

    validate() {
        if (this.state.email === "") {
            Alert.alert(
                '',
                'Email harus di isi!'
                ,
            )
        } else if (this.state.password === "") {
            Alert.alert(
                '',
                'Password harus di isi!'
                ,
            )
        } else if (this.state.confirm_pass === "") {
            Alert.alert(
                '',
                'Konfirmasi password harus di isi!'
                ,
            )
        } else if (this.state.confirm_pass !== this.state.password) {
            Alert.alert(
                '',
                'Password harus sama!'
                ,
            )
        }
        else if (this.state.full_name === "") {
            Alert.alert(
                '',
                'Nama harus di isi!'
                ,
            )
        } else if (this.state.dob_day === "") {
            Alert.alert(
                '',
                'Hari Lahir harus di isi!'
                ,
            )
        }
        else if (this.state.dob_day === "Pilih") {
            Alert.alert(
                '',
                'Hari Lahir harus di isi!'
                ,
            )
        } else if (this.state.dob_month === "") {
            Alert.alert(
                '',
                'Bulan lahir harus di isi!'
                ,
            )
        } else if (this.state.dob_month === "Pilih") {
            Alert.alert(
                '',
                'Bulan Lahir harus di isi!'
                ,
            )
        } else if (this.state.dob_year === "") {
            Alert.alert(
                '',
                'Tahun lahir harus di isi!'
                ,
            )
        } else if (this.state.dob_year === "Pilih") {
            Alert.alert(
                '',
                'Tahun Lahir harus di isi!'
                ,
            )
        } else if (this.state.gender === "") {
            Alert.alert(
                '',
                'Gender harus di isi!'
                ,
            )
        } else if (this.state.gender === "Pilih") {
            Alert.alert(
                '',
                'Gender  harus di isi!'
                ,
            )
        } else {
            this.handleReg()
        }
    }

    handleReg() {
        this.setState({
            spinner: true,
        })
        let parameter = {
            "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(),
            // "confirmation_number": this.state.confirmation_number,
            // "mobile_phone": this.state.no_hp,
            // "profession": this.state.profession,
            // "domicile": this.state.domicilie,
        }

        console.log(parameter);
        Axios.post(BASE_URL_REGISTER, parameter).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(
                '',
                'Email terkirim, mohon dicek'
                    ,
            )
            this.setState({
                spinner: false,
            })

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

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

    }
    render() {
        return (
            <View style={styles.container}>
                <ScrollView>
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <View style={styles.header}>
                    <StatusBar barStyle='dark-content' />
                    <Text style={styles.titleText}>{i18n.t('register')}</Text>
                </View>
                <View style={styles.body}>

                    <View style={styles.itemsRow}>
                        <View style={styles.items1}>
                            <Text>Email</Text>
                        </View>
                        <View style={styles.items2}>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 10 }}
                                onChangeText={(email) => this.setState({ email })}
                                value={this.state.email}
                                keyboardType='email-address'
                                autoCapitalize="none"
                            // autoCompleteType="email"
                            />
                        </View>
                    </View>
                    <View style={styles.itemsRow}>
                        <View style={styles.items1}>
                            <Text>{i18n.t('password')}</Text>
                        </View>
                        <View style={styles.items2}>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 10 }}
                                onChangeText={(password) => this.setState({ password })}
                                value={this.state.password}
                                secureTextEntry={true}
                            />
                        </View>
                    </View>
                    <View style={styles.itemsRow}>
                        <View style={styles.items1}>
                            <Text>{i18n.t('password2')}</Text>
                        </View>
                        <View style={styles.items2}>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 10 }}
                                onChangeText={(confirm_pass) => this.setState({ confirm_pass })}
                                value={this.state.confirm_pass}
                                secureTextEntry={true}
                            />
                        </View>
                    </View>
                    <View style={styles.itemsRow}>
                        <View style={styles.items1}>
                            <Text>{i18n.t('name')}</Text>
                        </View>
                        <View style={styles.items2}>
                            <TextInput
                                style={{ height: 40, borderColor: 'gray', borderWidth: 1, padding: 10 }}
                                onChangeText={(full_name) => this.setState({ full_name })}
                                value={this.state.full_name}
                            />
                        </View>
                    </View>
                    <View style={styles.itemsRow}>
                        <View style={styles.items1}>
                            <Text>{i18n.t('dob')}</Text>
                        </View>

                        <View style={styles.itemPicker}>

                            <View style={{ height: 35, flex: 1, borderLeftWidth: 1, borderTopWidth: 1, borderBottomWidth: 1 }}>
                                <Picker
                                    mode="dropdown"
                                    selectedValue={this.state.dob_day}
                                    style={{ height: 35, width: 100 }}
                                    onValueChange={(itemValue, itemIndex) => this.setState({ dob_day: itemValue })}>
                                    {date.map((itemValue, itemIndex) => {
                                        return (<Picker.Item label={itemValue} value={itemValue} key={itemIndex} />)
                                    })}

                                </Picker>
                            </View>
                            <View style={{ height: 35, flex: 1, borderLeftWidth: 1, borderTopWidth: 1, borderBottomWidth: 1 }}>

                                <Picker
                                    mode="dropdown"
                                    selectedValue={this.state.dob_month}
                                    style={{ height: 35, width: 100 }}
                                    onValueChange={(itemValue, itemIndex) =>
                                        this.setState({ dob_month: itemValue })
                                    }>
                                    {month.map((itemValue, itemIndex) => {
                                        return (<Picker.Item label={itemValue} value={itemIndex} key={itemIndex} />)
                                    })}
                                </Picker>
                            </View>
                            <View style={{ height: 35, flex: 1, borderLeftWidth: 1, borderTopWidth: 1, borderBottomWidth: 1, borderRightWidth: 1 }}>
                                <Picker
                                    mode="dropdown"
                                    selectedValue={this.state.dob_year}
                                    style={{ height: 35, width: 100 }}
                                    onValueChange={(itemValue, itemIndex) =>
                                        this.setState({ dob_year: itemValue })
                                    }>
                                    {year.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>{i18n.t('gender')}</Text>
                        </View>
                        <View style={styles.items3}>
                            <Picker selectedValue={this.state.gender}
                                onValueChange={(itemValue, itemIndex) => this.setState({ gender: itemValue })}>
                                <Picker.Item label='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>
                    <View style={styles.button}>
                        <Button title={i18n.t('register')} onPress={() => this.validate()} />
                    </View>
                    <View style={styles.signin}>
                        <TouchableOpacity onPress={() => this.props.navigation.navigate('Login')}>
                            <Text style={styles.textSignIn}>{i18n.t('signin')}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                </ScrollView>
            </View>
        )
    }
}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    header: {
        flex: 0.2,
        alignItems: 'center',
        justifyContent: 'center',
    },
    body: {
        flex: 0.8,
        flexDirection: 'column',
    },
    itemsRow: {
        flexDirection: 'row',
        marginTop: 25,
    },
    items1: {
        marginLeft: 15,
        width: 50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    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,
        marginHorizontal: 15
    },
    titleText: {
        margin:15,
        fontSize: 26,
        fontWeight: 'bold',
    },
    textInput: {
        borderWidth: 1,
        borderColor: 'black',
        height: 35,
        alignItems: 'stretch'
    },
    button: {
        marginTop: 25,
        marginHorizontal: 60,
        alignItems: 'stretch'
    },
    signin: {
        marginTop: 25,
        alignItems: 'center',
    },
    textSignIn: {
        color: 'red'
    }
})

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

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(null, mapDispatchToProps)(NewRegister);