import React from 'react';
import { View, Text, TextInput, StyleSheet, Button, Alert, TouchableOpacity, Image, Modal, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import Axios from 'axios';
import { Card } from 'react-native-shadow-cards'
import CheckBox from 'react-native-check-box'
import { Entypo, Ionicons, MaterialCommunityIcons, MaterialIcons, AntDesign, FontAwesome } from '@expo/vector-icons'
import ActionType from '../redux/globalActionType';
import Spinner from 'react-native-loading-spinner-overlay';
import PinRequest from './PinRequest'
import MyStatusBar from './MyStatusBar';
import i18n from 'i18n-js';

class UseBalance extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            kasproBalance: 0,
            kasproPoint: 0,
            current_balance: 0,
            kaspro_point: 0,
            input_redeem: 0,
            redeem_balance: 0,
            redeem_point: 0,
            modalVisible: false,
            pin: '',
            checkedBalance: false,
            checkedPoint: false,
            checkedBalancePoint: false,
            balanceused: 0,
            pointsused: 0,

        }
    }


    componentDidMount() {
        this._getProfile()
    }
    _getProfile() {
        let params = {
            session_id: this.props.session_id
        }

        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/get_profile', params).then(res => {
            // console.log('ini res ' + JSON.stringify(res.data))
            const dataCard = res.data


            let balance = dataCard.kaspro_balance.replace(',', '')
            let point = dataCard.kaspro_point.replace(',', '')
            let balances = parseFloat(balance);
            let points = parseFloat(point);


            this.setState({
                current_balance: dataCard.kaspro_balance,
                kaspro_point: dataCard.kaspro_point,
                kasproBalance: dataCard.kaspro_balance.replace(/,/g, ''),
                kasproPoint: dataCard.kaspro_point.replace(/,/g, '')
            })

            // // Buat Debug
            // this.setState({
            //     current_balance: '500,000',
            //     kaspro_point: '0',
            //     kasproBalance: '500,000'.replace(/,/g, ''),
            //     kasproPoint: '0'.replace(/,/g, '')
            // })

            // console.log("INI SESSION " + this.props.session_id)
            // console.log(this.state.kasproPoint)
        }).catch(error => {
            // console.log('ini error ' + error)
        })
    }

    checkedSelection(val) {
        // console.log(val)
        if (val == 'balance') {
            this.setState({
                checkedBalance: true,
                checkedPoint: false,
                checkedBalancePoint: false,
            })
        } else if (val == 'point') {
            this.setState({
                checkedBalance: false,
                checkedPoint: true,
                checkedBalancePoint: false,
            })
        } else {
            this.setState({
                checkedBalance: false,
                checkedPoint: false,
                checkedBalancePoint: true,
            })
        }
    }

    handleBack() {
        this.setState({
            modalVisible: false
        })
    }

    handleSubmit() {
        this.redeem()
        this.setState({
            modalVisible: false,
            pin: '',
        })
    }
    modal() {
        this.setState({
            modalVisible: true
        })
    }

    redeem() {

        if (this.state.checkedBalance == false && this.state.checkedPoint == false && this.state.checkedBalancePoint == false) {
            Alert.alert('Error', i18n.t('alertselectpayment') )
        } else {
            if (this.state.checkedBalance) {
                if (parseInt(this.state.input_redeem) > parseInt(this.state.kasproBalance)) {
                    Alert.alert('', i18n.t('alertbalance'))
                } else {
                    let params = {
                        session_id: this.props.session_id,
                        pin: this.state.pin,
                        balance: parseInt(this.state.input_redeem),
                        point: 0
                    }
                    console.log(params)

                    Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/point/redeem', params).then(res => {
                        // console.log(res.data)
                        let respon = res.data
                        // Alert.alert('', 'Sukses Redeem')

                        let redeemProps = {
                            in_payment: true,
                            redeem_code: respon.redeem_code,
                            balance_redeem: respon.use_balance,
                            point_redeem: respon.use_point
                        }

                        this.props.setRedeem(redeemProps)

                        this.props.navigation.navigate('Redeem Code')

                    }).catch(error => {
                        let response = error.response.data
                        if (response.code === "EMPTY_PIN") {
                            Alert.alert('Error', response.msg)
                        } else {
                            let response = error.response.data;
                            Alert.alert('', response.msg);
                        }

                    })
                }
            } else if (this.state.checkedPoint) {
                if (parseInt(this.state.input_redeem) > parseInt(this.state.kasproPoint)) {
                    Alert.alert('', i18n.t('alertpoin'))
                } else {
                    let params = {
                        session_id: this.props.session_id,
                        pin: this.state.pin,
                        balance: 0,
                        point: parseInt(this.state.input_redeem)
                    }
                    console.log(params)

                    Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/point/redeem', params).then(res => {
                        // console.log(res.data)
                        let respon = res.data
                        console.log("INI DATANYA " + respon)
                        // Alert.alert('', 'Sukses Redeem')
                        let redeemProps = {
                            in_payment: true,
                            redeem_code: respon.redeem_code,
                            balance_redeem: respon.use_balance,
                            point_redeem: respon.use_point
                        }

                        this.props.setRedeem(redeemProps)

                        this.props.navigation.navigate('Redeem Code')

                    }).catch(error => {
                        let response = error.response.data
                        if (response.code === "EMPTY_PIN") {
                            Alert.alert('Error', response.msg)
                        } else {
                            let response = error.response.data;
                            Alert.alert('', response.msg);
                        }

                    })
                }
            } else {
                if (parseInt(this.state.input_redeem) > parseInt(parseInt(this.state.kasproPoint) + parseInt(this.state.kasproBalance))) {
                    Alert.alert('', i18n.t('alertbalancepoin'))
                } else {
                    if (parseInt(this.state.kasproPoint) - parseInt(this.state.input_redeem) <= -1) {
                        // Alert.alert('masuk coy')
                        let params = {
                            session_id: this.props.session_id,
                            pin: this.state.pin,
                            balance: parseInt(this.state.input_redeem) - parseInt(this.state.kasproPoint),
                            point: parseInt(this.state.kasproPoint)
                        }
                        console.log(params)

                        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/point/redeem', params).then(res => {
                            let respon = res.data
                            console.log("INI DATANYA " + respon)
                            // Alert.alert('', 'Sukses Redeem')
                            let redeemProps = {
                                in_payment: true,
                                redeem_code: respon.redeem_code,
                                balance_redeem: respon.use_balance,
                                point_redeem: respon.use_point
                            }

                            this.props.setRedeem(redeemProps)

                            this.props.navigation.navigate('Redeem Code')

                        }).catch(error => {
                            let response = error.response.data
                            if (response.code === "EMPTY_PIN") {
                                Alert.alert('Error', response.msg)
                            } else {
                                let response = error.response.data;
                                Alert.alert('', response.msg);
                            }

                        })
                    } else {

                        let params = {
                            session_id: this.props.session_id,
                            pin: this.state.pin,
                            balance: 0,
                            point: parseInt(this.state.input_redeem)
                        }
                        console.log(params)

                        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/point/redeem', params).then(res => {
                            let respon = res.data
                            console.log("INI DATANYA " + respon)
                            // Alert.alert('', 'Sukses Redeem')
                            let redeemProps = {
                                in_payment: true,
                                redeem_code: respon.redeem_code,
                                balance_redeem: respon.use_balance,
                                point_redeem: respon.use_point
                            }

                            this.props.setRedeem(redeemProps)

                            this.props.navigation.navigate('Redeem Code')

                        }).catch(error => {
                            let response = error.response.data
                            if (response.code === "EMPTY_PIN") {
                                Alert.alert('Error', response.msg)
                            } else {
                                let response = error.response.data;
                                Alert.alert('', response.msg);
                            }

                        })
                    }
                }
            }

        }
    }

    render() {
        // console.log(parseInt(this.state.kasproPoint) - parseInt(this.state.input_redeem))
        // console.log(this.state.kasproBalance)
        // console.log(this.state.kasproPoint)
        return (
            <ScrollView style={styles.container}>
            <MyStatusBar />
                <Modal animationType="slide"
                    transparent={false}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {
                        this.setState({
                            modalVisible: false
                        })
                    }}>

                    <PinRequest />

                    {/* <View style={styles.centerViewModal}>
                        <View style={styles.modalView}>
                            <Text style={{ fontSize: 12, color: '#CFB368', fontFamily: 'Gotham-Black' }}>PIN</Text>
                            <View style={{ margin: 10 }}>
                                <TextInput
                                    style={styles.textInput}
                                    onChangeText={(pin) => this.setState({ pin })}
                                    value={this.state.pin}
                                    textAlign='center'
                                />
                            </View>
                            <View>
                            </View>
                            <View style={{margin:5}}>
                                <TouchableOpacity style={{marginBottom:10}} onPress={() => this.handleSubmit()}>
                                    <View style={styles.button2}>
                                        <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 16 }}>submit</Text>
                                    </View>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => this.handleBack()}>
                                    <View style={styles.button2}>
                                        <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 16 }}>Back</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View> */}

                </Modal>
                <View style={{ flex: 3 }}>
                    <View style={{ flex: 1, marginRight: 30, marginLeft: 30, top: 50 }}>
                        <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 3 }}>{i18n.t('balance')}</Text>

                        <Text style={{ fontFamily: 'Gotham-Black', color: '#838383', fontSize: 18, textAlign: 'center', margin: 1 }}>IDR {this.state.current_balance}</Text>

                        <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 3, marginTop: 10 }}>{i18n.t('point')}</Text>

                        <Text style={{ fontFamily: 'Gotham-Black', color: '#838383', fontSize: 18, textAlign: 'center', margin: 1 }}>IDR {this.state.kaspro_point}</Text>

                        {/* <TextInput style={{ height: 40, borderWidth: 1, padding: 5, margin: 10, borderRadius: 10, borderColor: 'grey', fontFamily: 'Gotham-Black', textAlign: 'center', color: 'grey', fontWeight: 'bold', fontSize: 20 }}
                            onChangeText={(redeem_balance) => this.setState({ redeem_balance })}
                            keyboardType='numeric'>{this.state.current_balance}</TextInput> */}

                        <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 3, marginTop: 10 }}>{i18n.t('redeem')}</Text>
                        <TextInput style={{ height: 40, borderWidth: 1, padding: 5, margin: 3, marginBottom: 20, borderRadius: 10, borderColor: 'grey', fontFamily: 'Gotham-Black', textAlign: 'center', color: 'grey', fontWeight: 'bold', fontSize: 20 }}
                            onChangeText={(input_redeem) => this.setState({ input_redeem })}
                            placeholder='0'
                            placeholderTextColor='#838383'
                            autoCapitalize="none"
                            keyboardType='numeric' />

                        <View style={{ alignItems: 'center' }}>

                            {
                                this.state.input_redeem == 0 || parseInt(this.state.input_redeem) > parseInt(this.state.kasproBalance) ? (
                                    <Card style={{ margin: 5, padding: 10, backgroundColor: 'gray' }}>
                                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                            <View>
                                                <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: 'white' }}>EXCELSO {i18n.t('balance')}</Text>
                                            </View>
                                            <View>
                                                <FontAwesome name='circle-o' size={30} color={'#ccb46c'} />
                                            </View>
                                        </View>
                                    </Card>
                                ) : (
                                        <TouchableOpacity onPress={() => {
                                            this.checkedSelection('balance')
                                        }}>
                                            <Card style={{ margin: 5, padding: 10 }}>
                                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                                    <View>
                                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: 'grey' }}>EXCELSO {i18n.t('balance')}</Text>
                                                    </View>
                                                    <View>
                                                        <CheckBox
                                                            onClick={() => {
                                                                this.checkedSelection('balance')
                                                            }}
                                                            isChecked={this.state.checkedBalance}
                                                            checkedImage={<FontAwesome name='check-circle' size={30} color={'#ccb46c'} />}
                                                            unCheckedImage={<FontAwesome name='circle-o' size={30} color={'#ccb46c'} />}
                                                        />
                                                    </View>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                    )
                            }
                        </View>
                        <View style={{ alignItems: 'center' }}>
                            {
                                this.state.input_redeem == 0 || parseInt(this.state.input_redeem) > parseInt(this.state.kasproPoint) ? (
                                    <Card style={{ margin: 5, padding: 10, backgroundColor: 'gray' }}>
                                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                            <View>
                                                <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: 'white' }}>EXCELSO {i18n.t('point')}</Text>
                                            </View>
                                            <View>
                                                <FontAwesome name='circle-o' size={30} color={'#ccb46c'} />
                                            </View>
                                        </View>
                                    </Card>
                                ) : (

                                        <TouchableOpacity onPress={() => {
                                            this.checkedSelection('point')
                                        }}>
                                            <Card style={{ margin: 5, padding: 10 }}>
                                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                                    <View>
                                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: 'grey' }}>EXCELSO {i18n.t('point')}</Text>
                                                    </View>
                                                    <View>
                                                        <CheckBox
                                                            onClick={() => {
                                                                this.checkedSelection('point')
                                                            }}
                                                            isChecked={this.state.checkedPoint}
                                                            checkedImage={<FontAwesome name='check-circle' size={30} color={'#ccb46c'} />}
                                                            unCheckedImage={<FontAwesome name='circle-o' size={30} color={'#ccb46c'} />}
                                                        />
                                                    </View>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                    )
                            }
                        </View>
                        <View style={{ alignItems: 'center' }}>
                            {
                                this.state.input_redeem == 0 || this.state.kasproPoint == 0 || parseInt(this.state.input_redeem) > parseInt(this.state.kasproPoint) + parseInt(this.state.kasproBalance) ? (
                                    <Card style={{ margin: 5, padding: 10, backgroundColor: 'gray' }}>
                                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                            <View>
                                                <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: 'white' }}>EXCELSO {i18n.t('balance')} + {i18n.t('point')}</Text>
                                            </View>
                                            <View>
                                                <FontAwesome name='circle-o' size={30} color={'#ccb46c'} />
                                            </View>
                                        </View>
                                    </Card>

                                ) : (
                                        <TouchableOpacity onPress={() => {
                                            this.checkedSelection('balancepoint')
                                        }}>
                                            <Card style={{ margin: 5, padding: 10 }}>
                                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                                    <View>
                                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Black', color: 'grey' }}>EXCELSO {i18n.t('balance')} + {i18n.t('point')}</Text>
                                                    </View>
                                                    <View>
                                                        <CheckBox
                                                            onClick={() => {
                                                                this.checkedSelection('balancepoint')
                                                            }}
                                                            isChecked={this.state.checkedBalancePoint}
                                                            checkedImage={<FontAwesome name='check-circle' size={30} color={'#ccb46c'} />}
                                                            unCheckedImage={<FontAwesome name='circle-o' size={30} color={'#ccb46c'} />}
                                                        />
                                                    </View>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>

                                    )
                            }
                        </View>
                        <TouchableOpacity style={{ height: 150 }} onPress={() => this.redeem()}>
                            <View style={{ backgroundColor: '#CFB368', height: 40, top: 20, borderRadius: 10, marginRight: 50, marginLeft: 50 }}>
                                <Text style={{ alignSelf: 'center', top: 10, color: 'white', fontFamily: 'Gotham-Black', fontSize: 20 }}>{i18n.t('redeem')}</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </ScrollView >
        )
    }
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: '#ffff'
    },

    header: {
        flex: 0.5,
        margin: 10,
    },

    form: {
        flex: 3,
        top: 40,
        margin: 10,
        marginTop: 0,
    },

    field_email: {
        flexDirection: 'row'
    },

    button: {
        height: 40,
        margin: 10,

    },
    logo: {
        alignSelf: 'flex-start',
        marginTop: 50,
        width: 290,
        height: 290,
        bottom: 145,

    },
    v_logo: {
        flex: 2,
        flexDirection: 'column-reverse',
        alignContent: 'flex-start',
    },
    centerViewModal: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
    },
    modalView: {
        backgroundColor: "white",
        borderRadius: 10,
        borderWidth: 1,
        borderColor: 'grey',
        padding: 20,
        alignItems: "center",
    },
    textInput: {
        height: 40,
        width: 250,
        borderColor: 'gray',
        borderWidth: 1,
        marginHorizontal: 30,
        borderRadius: 10
    },
    button2: {
        backgroundColor: '#CFB368',
        padding: 20,
        height: 40,
        borderRadius: 10,
        paddingVertical: 5,
        alignItems: 'center',
        justifyContent: 'center'
    },
})

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

const mapDispatchToProps = (dispacth) => {
    return {
        setRedeem: (redeemProps) => dispacth({
            type: ActionType.SET_REEDEM,
            data: {
                in_payment: redeemProps.in_payment,
                redeem_code: redeemProps.redeem_code,
                balance_redeem: redeemProps.balance_redeem,
                point_redeem: redeemProps.point_redeem
            }
        }),
    }
}

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