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 { FontAwesome } from '@expo/vector-icons';
import NumberFormat from 'react-number-format';
import MyStatusBar from './MyStatusBar';
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,
            transId: ''
        }
    }

    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 => {


                // 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: () => {
                            let data_order = res.data.data.id

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

                    ],
                    { cancelable: false }
                );
            }).catch(error => {
                let response = error.response.data;
                Alert.alert(
                    '', 
                    response.msg,
                    [
                        { text: "OK", onPress: () => 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 => {
                // 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: () => {
                            let data_order = res.data.data.id

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

                            this.orderSuccess()
                        } }

                    ],
                    { cancelable: false }
                );
            }).catch(error => {
                let response = error.response.data;
                Alert.alert(
                    '', 
                    response.msg,
                    [
                        { text: "OK", onPress: () => this.setState({spinner: false}) }
                    ],
                );
            })
        }
    }

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


    render() {
        // console.log(this.props.order_item)
        let total = 0
        return (
            <ScrollView style={styles.container}>
                <MyStatusBar />
                <Spinner
                    visible={this.state.spinner}
                    textContent={'Sedang Proses...'}
                    textStyle={styles.spinnerTextStyle}
                />
                {/* <View style={{ margin: 10, padding: 20, borderBottomWidth: 1 }}>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', textAlign: 'center' }}>{moment().utcOffset('+07:00').format('DD MMMM YYYY HH:mm:ss')}</Text>
                </View> */}
                <View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 1, borderColor: '#838383', margin: 10, paddingBottom: 20, 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.7, justifyContent: 'center' }}>
                                <Text style={{ textAlign: 'left', fontSize: 14, fontFamily: 'Gotham-Black', color: '#838383' }}>{this.props.name_outlet}</Text>
                                <Text style={{ textAlign: 'left', fontSize: 12, fontFamily: 'Gotham-Light', color: '#838383' }}>{this.props.outlet_detailadress}</Text>
                            </View>
                        ) : (
                                <View style={{ flex: 0.7, justifyContent: 'center' }}>
                                    <Text style={{ textAlign: 'left', fontSize: 14, fontFamily: 'Gotham-Black', color: '#838383' }}>{this.props.home_address}</Text>
                                    <Text style={{ textAlign: 'left', fontSize: 12, fontFamily: 'Gotham-Light', color: '#838383' }}>{this.props.address}</Text>
                                </View>

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

                            )
                    }
                </View>
                <View style={{ marginHorizontal: 10, paddingLeft: 10 }}>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: '#838383' }}>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.1, alignItems: 'center', justifyContent: 'center', alignItems: 'center', marginLeft: 18 }}>
                                        <Text style={{ fontSize: 20, fontFamily: 'Gotham-Light', color: '#838383' }}>{item.quantity}</Text>
                                    </View>
                                    <View style={{ flex: 0.2, alignItems: 'center' }}>
                                        <Image source={{ uri: item.image }} style={{ height: 50, width: 50, borderRadius: 5 }}></Image>
                                    </View>
                                    {/* <View style={{ flex: 0.1, alignItems: 'flex-start', justifyContent:'center', }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light' }}>x</Text>
                                    </View> */}
                                    <View style={{ flex: 0.4, alignItems: 'baseline', justifyContent: 'center', alignItems: 'flex-start', paddingLeft: 10 }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: '#838383' }}>{item.name} </Text>
                                        
                                        {
                                            (item.note == undefined || item.note == "") ? ( 
                                                null
                                            ) : (
                                                    <Text style={{ fontSize: 10, fontFamily: 'Gotham-Light', color: '#838383' }}>Keterangan : {item.note} </Text>
                                                )
                                        }

                                    </View>
                                    <View style={{ flex: 0.3, alignItems: 'flex-end', justifyContent: 'center', paddingRight: 5 }}>
                                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color:'#838383' }}>{item.quantity * item.price} </Text> */}
                                        <NumberFormat decimalScale={0} value={item.quantity * item.price} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: '#838383' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                    </View>
                                </View>
                            </View>
                        )
                    })
                }
                {
                    this.props.value_voucher == '' ? (
                        null
                    ) : (
                            <>
                                <View style={{ borderTopWidth: 1, borderColor: '#838383', margin: 10, padding: 10 }}>
                                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: '#838383' }}>VOUCHER</Text>
                                </View>

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

                    </View>
                </View>
                <View style={{ flexDirection: 'row', margin: 10, justifyContent: 'space-between' }}>

                    {this.props.type_pickup == true ? (
                        null
                    ) : (
                            <View>
                                <View style={{ margin: 10 }}>
                                    <Text>Delivery Charge</Text>
                                </View>

                                <View style={{ margin: 10 }}>
                                    <Text>{this.props.grabamount}</Text>
                                </View>
                            </View>
                        )}

                </View>
                <View style={{ flexDirection: 'row', margin: 10, justifyContent: 'space-between', borderTopWidth: 1 }}>
                    <View style={{ margin: 10 }}>
                        <Text>Total</Text>
                    </View>
                    {this.props.type_pickup == true ? (
                        <View style={{ margin: 10 }}>
                            {
                                this.props.value_voucher == '' ? (
                                    <Text>{this.props.order_total}</Text>
                                ) : (
                                        <Text>{Math.max(0, this.props.order_total - this.props.voucher.reward.value)}</Text>
                                    )
                            }
                        </View>
                    ) : (
                            <View style={{ margin: 10 }}>
                                {
                                    this.props.value_voucher == '' ? (
                                        <Text>{this.props.order_total + this.props.grabamount + this.state.diskon}</Text>
                                    ) : (
                                            <Text>{Math.max(this.props.order_total + this.props.grabamount - this.props.voucher.reward.value)}</Text>
                                        )
                                }

                            </View>
                        )}

                </View>

                {this.props.type_pickup == true ? (
                    null
                ) : (
                        <View style={{ flexDirection: 'row', margin: 10, justifyContent: 'space-between' }}>
                            <View style={{ margin: 10 }}>
                                <Text>Delivery to</Text>
                            </View>
                            <View style={{ margin: 10 }}>
                                <Text>{this.props.address}</Text>
                            </View>
                        </View>
                    )} */}
                {/* <View style={{ margin: 10 }}>
                    <Button title='order' onPress={() => this.setOrder(this.props.type_pickup)} />
                </View> */}
                <TouchableOpacity onPress={() => this.setOrder(this.props.type_pickup)}>
                    <View style={styles.button}>
                        <Text style={{ color: 'white', fontSize: 16, 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: 40,
        borderRadius: 10,
        height: 40,
        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,
        home_address: state.home_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,
        outlet_detailadress: state.outlet_detailadress,
        lat: state.lat,
        long: state.long
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MenuConfirmation)
