import React, { useState } from 'react'
import { Camera } from 'expo-camera';
import * as Permissions from 'expo-permissions';
import Axios from 'axios';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import * as FileSystem from 'expo-file-system';
import Spinner from 'react-native-loading-spinner-overlay';
import RNPickerSelect from 'react-native-picker-select';
import {
    View,
    Text,
    Picker,
    TextInput,
    StyleSheet,
    ScrollView,
    Button,
    Image,
    TouchableOpacity,
    Alert
} from 'react-native'


const jobs = ["Pilih", "Siswa", "Mahasiswa", "Karyawan", "Pengusaha", "Lainnya"]
class UpgradePremium extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            nama_depan: '',
            nama_belakang: '',
            Ktp: '',
            tempat_lahir: '',
            mother_name: '',
            gaji: '',
            pekerjaan: '',
            alamat_permanent: '',
            alamat_sekarang: '',
            birthDate: '',
            gender: '',
            region: '',
            city: '',
            district: '',
            village: '',
            id_type: 'KTP',
            id_value: '',
            nationality: '',
            provinces : [],
            hasPermissions: null,
            type: Camera.Constants.Type.back,
            uri_id : this.props.URI,
            uri_selfie : this.props.URI_IDCARD,
            spinner: false
        }
    }


    async componentDidMount() {
        // const { status } = await Permissions.askAsync(Permissions.CAMERA);
        // this.setState({ hasPermissions: status === 'granted' });
        this.getProfile()
        this.getProvince()
        // console.log(this.props)
    }

    takePictureSelfie = () => {
        let UriImgProps = {
            selfie: true
        }

        this.props.setImageCapture(UriImgProps);
        this.props.navigation.navigate("Camera")
    };

    takePictureIdcard = () => {
        let UriidProps = {
            idcard: true
        }
        this.props.setIDCapture(UriidProps);
        this.props.navigation.navigate("Camera")
    };

    getProfile() {
        let params = {
            session_id: this.props.session_id
        }
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/get_profile', params).then(res => {
            let data = res.data
            this.setState({
                birthDate: data.dob_day + "-" + data.dob_month + "-" + data.dob_year,
                gender: data.gender_display
            })
        }).catch(error => {
            let response = error.response.data;
            Alert.alert(response.msg);
        })
    }

    getProvince(){
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/get_province').then(res => {
            let dataProv = res.data.data
            // console.log('ini res nya prov : ' + JSON.stringify(dataProv))
            let list_prov = []
            for (const prov in dataProv) {
                // console.log(dataProv[prov])
                if (dataProv.hasOwnProperty(prov)) {
                    const label = dataProv[prov].name
                    const value = dataProv[prov].name + '-' + dataProv[prov].id
                    list_prov.push({ label: label, value: value })
                }
                // console.log( 'ini isi list prov : ' + JSON.stringify(list_prov))
            }

            this.setState({
                provinces : list_prov
            })
            // console.log('ini hasilnya : ' + JSON.stringify(this.state.provinces))
        })
    }

    async handlePremium() {
        this.setState({
            spinner: true,
        })
        const URI = await FileSystem.readAsStringAsync(this.state.uri_selfie,{encoding: FileSystem.EncodingType.Base64 });
        const URI_IDCARD = await FileSystem.readAsStringAsync(this.state.uri_id,{ encoding: FileSystem.EncodingType.Base64 });
        // const URI = await FileSystem.readAsStringAsync(this.state.uri_selfie,{encoding:'base64'});
        let params = {
            session_id: this.props.session_id,
            first_name: this.state.nama_depan,
            last_name: this.state.nama_belakang,
            birth_place: this.state.tempat_lahir,
            birth_date: this.state.birthDate,
            gender: this.state.gender,
            address_permanent: this.state.alamat_permanent,
            region: this.state.region,
            city: this.state.city,
            specific_address: this.state.alamat_permanent,
            district: this.state.district,
            village: this.state.village,
            occupation: this.state.pekerjaan,
            id_type: this.state.id_type,
            id_value: this.state.id_value,
            nationality: this.state.nationality,
            customer_image: URI_IDCARD,
            id_card_image: URI
        }

        // console.log(params.customer_image);
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/card/upgrade_premium', params).then(res => {
            console.log('ini res ' + JSON.stringify(res.data))
            Alert.alert(
                '',
                'Permintaan upgrade premium anda telah kami terima, mohon menunggu 1x24 jam!'
                ,
            )
            this.setState({
                spinner: false,
            })
            navigation.reset({
                index: 0,
                routes: [
                  {
                    name: 'Home',
                    params: { someParam: 'Param1' },
                  },
                ],
              })
        }).catch(error => {
            let response = error.response.data;
            Alert.alert(
                '',
                response.msg,
            )
            this.setState({
                spinner: false,
            })
            this.props.navigation.reset({
                index: 0,
                routes: [
                  {
                    name: 'Home',
                  },
                ],
              })
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <ScrollView>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Nama Depan</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(nama_depan) => this.setState({ nama_depan })}
                            value={this.state.nama_depan}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Nama Belakang</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(nama_belakang) => this.setState({ nama_belakang })}
                            value={this.state.nama_belakang}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Tempat Lahir</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(tempat_lahir) => this.setState({ tempat_lahir })}
                            value={this.state.tempat_lahir}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Alamat Permanen</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 90, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(alamat_permanent) => this.setState({ alamat_permanent })}
                            value={this.state.alamat_permanent}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Provinsi</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(region) => this.setState({ region })}
                            value={this.state.region}
                        />
                        {/* <RNPickerSelect
                                value={this.state.region}
                                placeholderTextColor='gray'
                                onValueChange={(value) => this.setState({ region : value})}
                                items= {this.state.provinces} /> */}
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Kota</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(city) => this.setState({ city })}
                            value={this.state.city}
                        />
                        {/* <RNPickerSelect
                                value={this.state.city}
                                placeholderTextColor='gray'
                                onValueChange={(value) => this.setState({ city : value})}
                                items= {this.state.provinces} /> */}
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Kecamatan</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(district) => this.setState({ district })}
                            value={this.state.district}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Kelurahan</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(village) => this.setState({ village })}
                            value={this.state.village}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Pekerjaan</Text>
                    </View>
                    <View style={{ margin: 10, borderColor: 'gray', borderWidth: 1 }}>
                        <Picker
                            mode="dropdown"
                            selectedValue={this.state.pekerjaan}
                            style={{ height: 40 }}
                            onValueChange={(itemValue, itemIndex) => this.setState({ pekerjaan: itemValue })}>
                            {jobs.map((itemValue, itemIndex) => {
                                return (<Picker.Item label={itemValue} value={itemValue} key={itemIndex} />)
                            })}

                        </Picker>
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>KTP</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(id_value) => this.setState({ id_value })}
                            value={this.state.id_value}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Kebangsaan</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                            onChangeText={(nationality) => this.setState({ nationality })}
                            value={this.state.nationality}
                        />
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Upload Foto Diri</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TouchableOpacity onPress={() => this.takePictureSelfie()}>
                            <View style={{ height: 90, borderColor: 'gray', borderWidth: 1 }}>
                                {
                                    this.props.URI === '' ?(
                                        null
                                    ):(

                                        <Image
                                            style={{ width: 90, height: 80, alignSelf: 'center', }}
                                            source={{ uri: this.props.URI }}
                                        />
                                    )
                                }
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10 }}>
                        <Text style={{ top: 5 }}>Upload Foto KTP</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TouchableOpacity onPress={() => this.takePictureIdcard()}>
                            <View style={{ height: 90, borderColor: 'gray', borderWidth: 1 }}>
                                {
                                    this.props.URI_IDCARD === '' ? (
                                        null
                                    ):(
                                        <Image
                                            style={{ width: 90, height: 80, alignSelf: 'center', }}
                                            source={{ uri: this.props.URI_IDCARD }}
                                        />
                                    )
                                }
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={{ marginRight: 10, marginLeft: 10, marginBottom: 15 }}>
                        <Button
                            title="Upgrade Premium"
                            onPress={() => this.handlePremium()}
                        />
                    </View>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'

    }
})

const mapDispatchToProps = (dispacth) => {
    return {
        setImageCapture: (UriImgProps) => dispacth({
            type: ActionType.SET_CHANGE_IMAGE_SELFI,
            data: {
                selfie: UriImgProps.selfie
            }
        }),
        setIDCapture: (UriidProps) => dispacth({
            type: ActionType.SET_CHANGE_IMAGE_ID,
            data: {
                idcard: UriidProps.idcard
            }
        })
    }


}

const mapStateToProps = (state) => {
    return {

        session_id: state.session_id,
        URI: state.URI,
        URI_IDCARD: state.URI_IDCARD,
        BASE64_ID: state.BASE64_ID,
        BASE64_SELFIE: state.BASE64_SELFIE,
        img64: state.img64,
        id_card64: state.id_card64
    }
}

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