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 * as ImageManipulator from "expo-image-manipulator";
import {
    View,
    Text,
    Picker,
    TextInput,
    StyleSheet,
    ScrollView,
    Button,
    Image,
    TouchableOpacity,
    Alert
} from 'react-native'
import MyStatusBar from './MyStatusBar';
import i18n from 'i18n-js';

const jobs = ["Pilih", "Siswa", "Mahasiswa", "Karyawan", "Pengusaha", "Lainnya"];
const _jobs = [
    {label: "Siswa", value: "Siswa"}, 
    {label: "Mahasiswa", value: "Mahasiswa"}, 
    {label: "Karyawan", value: "Karyawan"}, 
    {label: "Pengusaha", value: "Pengusaha"}, 
    {label: "Lainnya", value: "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,
            caretHidden:true,
        }
    }


    async componentDidMount() {
        // const { status } = await Permissions.askAsync(Permissions.CAMERA);
        // this.setState({ hasPermissions: status === 'granted' });
        this.getProfile()
        this.getProvince()
        console.log("INI AKAKAKAK"+ JSON.stringify(this.props.URI))
    }

    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 manipResultSelfie= await ImageManipulator.manipulateAsync(
            this.props.URI,
            [{ resize: { width: 1000, height: 1000 } }], // resize to width of 300 and preserve aspect ratio 
            { compress: 0.4, format: 'jpeg', },
          );

          const manipResultidCard= await ImageManipulator.manipulateAsync(
            this.props.URI_IDCARD,
            [{ resize: { width: 1000, height: 1000 } }], // resize to width of 300 and preserve aspect ratio 
            { compress: 0.4, format: 'jpeg', },
          );
         
        const URI_IDCARD = await FileSystem.readAsStringAsync(manipResultidCard.uri, { encoding: 'base64' });
        const URI = await FileSystem.readAsStringAsync(manipResultSelfie.uri,{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,
            id_card_image: URI_IDCARD
        }

        // 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,
            )
            // console.log("INI BASE64 SELFI :" + URI)
            // console.log("INI BASE64 ID :" + URI_IDCARD)
            this.setState({
                spinner: false,
            })
            this.props.navigation.reset({
                index: 0,
                routes: [
                    {
                        name: 'Home',
                    },
                ],
            })
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <MyStatusBar />
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <ScrollView>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('firstName')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(nama_depan) => this.setState({ nama_depan })}
                            value={this.state.nama_depan}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('lastName')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(nama_belakang) => this.setState({ nama_belakang })}
                            value={this.state.nama_belakang}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('birthPlace')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(tempat_lahir) => this.setState({ tempat_lahir })}
                            value={this.state.tempat_lahir}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('permanentAddress')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput2}
                            onChangeText={(alamat_permanent) => this.setState({ alamat_permanent })}
                            value={this.state.alamat_permanent}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('province')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(region) => this.setState({ region })}
                            value={this.state.region}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                        {/* <RNPickerSelect
                                value={this.state.region}
                                placeholderTextColor='gray'
                                onValueChange={(value) => this.setState({ region : value})}
                                items= {this.state.provinces} /> */}
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('city')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(city) => this.setState({ city })}
                            value={this.state.city}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                        {/* <RNPickerSelect
                                value={this.state.city}
                                placeholderTextColor='gray'
                                onValueChange={(value) => this.setState({ city : value})}
                                items= {this.state.provinces} /> */}
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('village')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(district) => this.setState({ district })}
                            value={this.state.district}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('district')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(village) => this.setState({ village })}
                            value={this.state.village}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('job')}</Text>
                    </View>
                    <View style={{ marginHorizontal: 40, borderColor: 'gray', borderWidth: 1, borderRadius: 10, top: 10 }}>
                    {Platform.OS === 'ios' ? (
                    <RNPickerSelect onValueChange={(value) => this.setState({ pekerjaan: value })}
                        items={_jobs}
                        placeholder={{ label: '-- Select --' }}
                        style={{inputIOSContainer: {paddingVertical: 10, alignItems: 'center'}}}
                    />
                    ) : (
                    <Picker
                        mode="dropdown"
                        selectedValue={this.state.pekerjaan}
                        style={{ height: 40, width: '100%' }}
                        onValueChange={(itemValue, itemIndex) => this.setState({ pekerjaan: itemValue })}>
                        {jobs.map((itemValue, itemIndex) => {
                            return (<Picker.Item label={itemValue} value={itemValue} key={itemIndex} />)
                        })}

                    </Picker>
                    )}

                    </View>
                    <View style={styles.textLabel, { top: 20 }}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('idCard')}</Text>
                    </View>
                    <View style={{ margin: 10, marginTop: 23 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(id_value) => this.setState({ id_value })}
                            value={this.state.id_value}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('nationality')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TextInput
                            style={styles.textInput}
                            onChangeText={(nationality) => this.setState({ nationality })}
                            value={this.state.nationality}
                            textAlign='center'
                            caretHidden={this.state.caretHidden}
                            onFocus={() => this.setState({caretHidden: false})}
                        />
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('selfieImage')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TouchableOpacity onPress={() => this.takePictureSelfie()}>
                            <View style={{ height: 90, borderColor: 'gray', borderWidth: 1, borderRadius: 10, marginHorizontal: 30 }}>
                                {
                                    this.props.URI === '' ? (
                                        null
                                    ) : (

                                            <Image
                                                style={{ width: 90, height: 80, alignSelf: 'center', }}
                                                source={{ uri: this.props.URI }}
                                            />
                                        )
                                }
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.textLabel}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: '#CFB368', textAlign: 'center' }}>{i18n.t('idCardImage')}</Text>
                    </View>
                    <View style={{ margin: 10 }}>
                        <TouchableOpacity onPress={() => this.takePictureIdcard()}>
                            <View style={{ height: 90, borderColor: 'gray', borderWidth: 1, borderRadius: 10, marginHorizontal: 30 }}>
                                {
                                    this.props.URI_IDCARD === '' ? (
                                        null
                                    ) : (
                                            <Image
                                                style={{ width: 90, height: 80, alignSelf: 'center', }}
                                                source={{ uri: this.props.URI_IDCARD }}
                                            />
                                        )
                                }
                            </View>
                        </TouchableOpacity>
                    </View>
                    <TouchableOpacity onPress={() => this.handlePremium()}>
                        <View style={styles.button}>
                            <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 20 }}>{i18n.t('upgradePremium')}</Text>
                        </View>
                    </TouchableOpacity>
                    <View style={{height:30}}/>
                    {/* <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'

    },
    textLabel: {
        marginRight: 10,
        marginLeft: 10,
        top: 5
    },
    textInput: {
        height: 40,
        borderColor: 'gray',
        borderWidth: 1,
        marginHorizontal: 30,
        borderRadius: 10
    },
    textInput2: {
        height: 90,
        borderColor: 'gray',
        borderWidth: 1,
        marginHorizontal: 30,
        borderRadius: 10
    },
    button: {
        backgroundColor: '#CFB368',
        marginTop: 25,
        marginHorizontal: 50,
        borderRadius: 15,
        paddingVertical: 5,
        alignItems: 'center',
        justifyContent: 'center'
    },
})

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