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


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: [],
            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,
            })
        })
    }

    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(this.props.BASE_URL+'crm/v2/auth/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 => {

            // 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
                                    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
                                    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}
                                    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}
                                    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: 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, alignItems: 'center' }}>
                                            <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, alignItems: 'center' }}>
                                            <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 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='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);