import React from 'react';
import { View, Text, Alert, TouchableOpacity, StyleSheet, Button, ScrollView, Image } from 'react-native';
import Axios from 'axios'
import { connect } from 'react-redux'
import ActionType from '../redux/globalActionType';
import Spinner from 'react-native-loading-spinner-overlay';
import session from '../function/session';
import moment from 'moment'
import NumberFormat from 'react-number-format';
import { FontAwesome } from '@expo/vector-icons';
class MenuConfirmation extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            kasproBalance: '',
            kasproPoint: '',
            balanceused: 0,
            pointsused: 0,
            ongkir: 0,
            diskon: 0,
            totalOrder: 0,
            type: '',
            spinner: false,
        }
    }

    componentDidMount() {
        // console.log(" DESTINASI : "+ this.props.grabdestination)
        // console.log("ONGKIR"+ this.props.grabamount)
        // console.log("drop off"+this.props.grabdropoff)
        // console.log("pickup"+this.props.grabpickup)
        // console.log("type" +this.props.grabtype)
        // console.log("BALANCED" +this.props.balanceUsed)
        // console.log("POINT" +this.props.pointsused)
        // console.log(this.props.type_pickup)
        // console.log('kosong'+this.props.value_voucher)


    }

    setOrder(is_pickup) {
        this.setState({
            spinner: true,
        })
        // console.log(is_pickup)
        if (is_pickup) {
            this.setState({
                type: 'Pick Up'
            })
        } else {
            this.setState({
                type: 'Delivery'
            })
        }
        // console.log(this.state.type)
        // console.log(is_pickup)

        if (this.props.value_voucher == '') {
            let params = {
                session_id: this.props.session_id,
                outlet_id: this.props.outlet_id,
                address_id: this.props.addressId,
                trans_type: this.props.type_pickup ? 'Pick Up' : 'Delivery',
                order_item: this.props.order_item,
                delivery_charge: this.props.grabamount,
                voucher: [],
                payment: {
                    balance: this.props.route.params.balanceUsed,
                    point: this.props.route.params.pointused
                }
            }

            console.log(params)

            Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/transaction/booking', params).then(res => {
                let data_order = res.data.data.id

                this.setState({
                    spinner: false,
                })
                let transIdProps = {
                    trans_id: data_order
                }
                this.props.setTransId(transIdProps);

                // add API use voucher here
                // let param = {
                //     session_id: this.props.session_id,
                //     reward_id: this.props.voucher.id,
                //     lat: this.props.lat,
                //     long: this.props.long
                // }

                // Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/reward/use_reward', param).then(res => {
                //         console.log(res.data)
                // }).catch(error => {
                //     const { navigation } = this.props
                //     let response = error.response.data
                //     session(response, navigation)
                //     Alert.alert(response.msg);
                //     this.setState({
                //         spinner: false,
                //     })
                // })

                Alert.alert(
                    "Berhasil",
                    "Transaksi sudah berhasil, terimakasih sudah menggunakan excelso untuk ngopi",
                    [
                        { text: "OK", onPress: () => this.orderSuccess() }

                    ],
                    { cancelable: false }
                );
            }).catch(error => {
                // const { navigation } = this.props
                // let response = error.response.data
                // session(response, navigation)
                console.log(error)
                Alert.alert('error', error.response.msg);
                this.setState({
                    spinner: false,
                })
            })

        } else {
            let params = {
                session_id: this.props.session_id,
                outlet_id: this.props.outlet_id,
                address_id: this.props.addressId,
                trans_type: this.props.type_pickup ? 'Pick Up' : 'Delivery',
                order_item: this.props.order_item,
                delivery_charge: this.props.grabamount,
                voucher: [{
                    value: this.props.voucher.reward.value,
                    verification_number: this.props.voucher.verification_number
                }],
                payment: {
                    balance: this.props.route.params.balanceUsed,
                    point: this.props.route.params.pointused
                }
            }

            console.log(params)

            Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/transaction/booking', params).then(res => {
                let data_order = res.data.data.id

                this.setState({
                    spinner: false,
                })
                let transIdProps = {
                    trans_id: data_order
                }
                this.props.setTransId(transIdProps);

                // add API use voucher here
                // let param = {
                //     session_id: this.props.session_id,
                //     reward_id: this.props.voucher.id,
                //     lat: this.props.lat,
                //     long: this.props.long
                // }

                // Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/reward/use_reward', param).then(res => {
                //         console.log(res.data)
                // }).catch(error => {
                //     const { navigation } = this.props
                //     let response = error.response.data
                //     session(response, navigation)
                //     Alert.alert(response.msg);
                //     this.setState({
                //         spinner: false,
                //     })
                // })

                Alert.alert(
                    "Berhasil",
                    "Transaksi sudah berhasil, terimakasih sudah menggunakan excelso untuk ngopi",
                    [
                        { text: "OK", onPress: () => this.orderSuccess() }

                    ],
                    { cancelable: false }
                );
            }).catch(error => {
                // const { navigation } = this.props
                // let response = error.response.data
                // session(response, navigation)
                Alert.alert(error.response.msg);
                this.setState({
                    spinner: false,
                })
            })
        }
    }

    orderSuccess = () => {
        this.props.setOrderFinish()
        this.props.navigation.navigate('Order Detail');
        // this.props.navigation.reset({
        //     routes: [{ name: 'Home' }]
        // })
    }


    render() {
        console.log(this.props.session_id)
        let total = 0
        return (
            <ScrollView style={styles.container}>
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Sedang Proses...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <View style={{ margin: 10, padding: 20, borderBottomWidth: 1, borderColor: 'grey' }}>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', textAlign: 'center', color: 'grey' }}>{moment().utcOffset('+07:00').format('DD MMMM YYYY HH:mm:ss')}</Text>
                </View>
                <View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 1, borderColor: 'grey', margin: 10, paddingBottom: 30, padding: 10 }}>
                    <View style={{ flex: 0.1, justifyContent: 'center' }}>
                        <FontAwesome name="map-marker" size={24} color="red" />
                    </View>
                    {
                        this.props.type_pickup == true ? (
                            <View style={{ flex: 0.6, justifyContent: 'center' }}>
                                <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{this.props.name_outlet}</Text>
                            </View>
                        ) : (
                                <View style={{ flex: 0.6, justifyContent: 'center' }}>
                                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{this.props.address}</Text>
                                </View>

                            )
                    }
                    {
                        this.props.type_pickup == true ? (
                            <View style={{ flex: 0.3, justifyContent: 'center' }}>
                                <Text style={{ textAlign: 'right', fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>PICKUP</Text>
                            </View>
                        ) : (
                                <View style={{ flex: 0.3, justifyContent: 'center' }}>
                                    <Text style={{ textAlign: 'right', fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>DELIVERY</Text>
                                </View>

                            )
                    }
                </View>
                <View style={{ marginHorizontal: 10, paddingLeft: 10 }}>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Pesanan</Text>
                </View>
                {
                    this.props.order_item.map((item, index) => {
                        total = total + item.quantity * item.price
                        return (
                            <View style={{ margin: 0 }} key={index} >
                                <View style={{ flex: 1, margin: 10, flexDirection: 'row', justifyContent: 'space-around' }}>
                                    <View style={{ flex: 0.3, alignItems: 'center' }}>
                                        <Image source={{ uri: item.image }} style={{ height: 50, width: 50, borderRadius: 5 }}></Image>
                                    </View>
                                    <View style={{ flex: 0.1, alignItems: 'center', justifyContent: 'center', }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{item.quantity}</Text>
                                    </View>
                                    <View style={{ flex: 0.1, alignItems: 'flex-start', justifyContent: 'center', }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>x</Text>
                                    </View>
                                    <View style={{ flex: 0.3, alignItems: 'baseline', justifyContent: 'center', }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{item.name} </Text>
                                    </View>
                                    <View style={{ flex: 0.3, alignItems: 'flex-end', justifyContent: 'center', }}>
                                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light' }}>{item.quantity * item.price} </Text> */}
                                        <NumberFormat decimalScale={0} value={item.quantity * item.price} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                    </View>
                                </View>
                            </View>
                        )
                    })
                }
                {
                    this.props.value_voucher == '' ? (
                        null
                    ) : (
                            <>
                                <View style={{ borderTopWidth: 1, borderColor: 'grey', margin: 10, padding: 10 }}>
                                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Voucher</Text>
                                </View>

                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', margin: 10, marginTop: -10 }}>
                                    <View style={{ margin: 10, paddingLeft: 10 }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{this.props.voucher.reward.title}</Text>
                                    </View>
                                    <TouchableOpacity onPress={() => this.props.navigation.navigate('Reward Detail', { rewardId: this.props.voucher.id })}>
                                        <View style={{ margin: 10, paddingRight: 5 }}>
                                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: '#CFB368' }}>View Detail</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            </>
                        )
                }
                <View style={{ borderTopWidth: 1, borderColor: 'grey', marginHorizontal: 10, paddingLeft: 10, padding: 10 }}>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Payment</Text>
                </View>
                <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginTop: -10 }}>
                    <View style={{ flex: 0.5, margin: 10, paddingLeft: 20 }}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Balance Used</Text>
                    </View>
                    <View style={{ flex: 0.5, margin: 10, alignItems: 'flex-end', paddingRight: 5 }}>
                        <NumberFormat decimalScale={0} value={this.props.route.params.balanceUsed} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                    </View>
                </View>
                <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginTop: -10 }}>
                    <View style={{ flex: 0.5, margin: 10, paddingLeft: 20 }}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Point Used</Text>
                    </View>
                    <View style={{ flex: 0.5, margin: 10, alignItems: 'flex-end', paddingRight: 5 }}>
                        <NumberFormat decimalScale={0} value={this.props.route.params.pointused} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                    </View>
                </View>
                <View style={{ borderTopWidth: 1, borderColor: 'grey', margin: 10, paddingLeft: 10, padding: 10, paddingBottom: -10, flexDirection: 'row', justifyContent: 'space-between', flex: 1 }}>
                    <View style={{ flex: 0.6 }}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Harga</Text>
                    </View>
                    <View style={{ flex: 0.4, marginRight: -5 }}>
                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color:'grey', textAlign: 'right' }}>{total}</Text> */}
                        <NumberFormat decimalScale={0} value={total} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', textAlign: 'right' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                    </View>
                </View>
                {
                    this.props.value_voucher == '' ? (
                        null
                    ) : (
                            <View style={{ margin: 10, marginTop: -10, paddingLeft: 10, padding: 20, paddingBottom: -10, flexDirection: 'row', justifyContent: 'space-between', flex: 1, flexDirection: 'row' }}>
                                <View style={{ flex: 0.6 }}>
                                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Voucher</Text>
                                </View>
                                <View style={{ flex: 0.4, marginRight: -5 }}>
                                    <NumberFormat decimalScale={0} value={this.props.voucher.reward.value} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', textAlign: 'right' }}>- Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                </View>
                            </View>
                        )
                }
                {
                    this.props.type_pickup == true ? (
                        null
                    ) : (
                            <View style={{ margin: 10, marginTop: -10, paddingLeft: 10, padding: 20, paddingBottom: -10, flexDirection: 'row', justifyContent: 'space-between', flex: 1, flexDirection: 'row' }}>
                                <View style={{ flex: 0.6 }}>
                                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Ongkos Kirim</Text>
                                </View>
                                <View style={{ flex: 0.4, marginRight: -5 }}>
                                    <NumberFormat decimalScale={0} value={this.props.grabamount} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', textAlign: 'right' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                </View>
                            </View>
                        )
                }
                <View style={{ marginHorizontal: 7, paddingHorizontal: 10, flexDirection: 'row', justifyContent: 'space-between', flex: 1 }}>
                    <View style={{ flex: 0.6 }}>
                        <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', color: '#CFB368' }}>Total</Text>
                    </View>
                    {
                        this.props.value_voucher == '' ? (
                            <View style={{ flex: 0.4, marginRight: -5, }}>
                                {/* <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', textAlign: 'right', color: '#CFB368' }}>{this.props.order_total + this.props.grabamount}</Text> */}
                                <NumberFormat decimalScale={0} value={this.props.order_total + this.props.grabamount} renderText={value => <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', textAlign: 'right', color: '#CFB368' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                            </View>
                        ) : (
                                <View style={{ flex: 0.4, marginRight: -5, }}>
                                    {/* <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', textAlign: 'right', color: '#CFB368' }}>{Math.max(0, this.props.order_total - this.props.voucher.reward.value + this.props.grabamount)}</Text> */}
                                    <NumberFormat decimalScale={0} value={Math.max(0, this.props.order_total - this.props.voucher.reward.value + this.props.grabamount)} renderText={value => <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', textAlign: 'right', color: '#CFB368' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                </View>
                            )
                    }

                </View>
                <TouchableOpacity onPress={() => this.setOrder(this.props.type_pickup)}>
                    <View style={styles.button}>
                        <Text style={{ color: 'white', fontSize: 22, fontFamily: 'Gotham-Black' }}>Proses Pesanan</Text>
                    </View>
                </TouchableOpacity>
                <View style={{ height: 30 }} />
            </ScrollView>
        )
    }
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    header: {

        flex: 0.5,
    },
    images: {
        margin: 10,
        flex: 2,
        backgroundColor: 'green'
    },
    content: {
        flex: 2,
    },
    body: {
        flex: 3,
    },
    button: {
        backgroundColor: '#CFB368',
        marginTop: 25,
        marginHorizontal: 30,
        borderRadius: 10,
        paddingVertical: 5,
        alignItems: 'center',
        justifyContent: 'center'
    },

})


const mapDispatchToProps = (dispacth) => {
    return {
        setOrderFinish: () => dispacth({
            type: ActionType.SET_ORDER_FINISH
        }),
        setTransId: (transIdProps) => dispacth({
            type: ActionType.SET_TRANS_ID,
            data: {
                trans_id: transIdProps.trans_id,
            }
        })
    }
}

const mapStateToProps = (state) => {
    // console.log(state)
    return {
        session_id: state.session_id,
        value_voucher: state.value_voucher,
        voucher: state.voucher,
        type_pickup: state.type_pickup,
        outlet_id: state.outlet_id,
        order_quantity: state.order_quantity,
        order_total: state.order_total,
        order_item: state.order_item,
        quantity: state.quantity,
        address: state.address,
        grabtype: state.grabtype,
        grabamount: state.grabamount,
        grabpickup: state.grabpickup,
        grabdropoff: state.grabdropoff,
        grabdestination: state.grabdestination,
        balanceUsed: state.balanceUsed,
        pointused: state.pointused,
        address: state.address,
        addressId: state.addressId,
        outlet_id: state.outlet_id,
        name_outlet: state.name_outlet,
        lat: state.lat,
        long: state.long
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MenuConfirmation)
