import React from 'react';
import { View, Text, TextInput, StyleSheet, ScrollView, Alert, TouchableOpacity, BackHandler, Modal, Image } from 'react-native';
import { Card } from 'react-native-shadow-cards'
import { connect } from 'react-redux';
import Axios from 'axios';
import { Rating, AirbnbRating } from 'react-native-elements';
import session from '../function/session';
import moment from 'moment'
import NumberFormat from 'react-number-format';
import { FontAwesome } from '@expo/vector-icons';

class OrderDetail extends React.Component {

    constructor(props) {
        super(props)
        this.handleBackButtonClick = this.handleBackButtonClick.bind(this)
        this.state = {
            trans_type_display: '',
            outlet: '',
            outlet_code: '',
            trans_status_display: '',
            transaction_detail: [],
            numberId: '',
            detail_trans: '',
            trans_status: '',
            modalVisible: false,
            reason: '',
            is_reviewed: '',
            review_rating: 0
        }


    }


    componentDidMount() {

        BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
        this.getDetailTrans()

    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
    }


    handleBackButtonClick() {
        this.props.navigation.navigate('Home', { screen: 'ORDER' });
        return true;
    }

    handleCancel() {
        // this.setState({
        //     modalVisible: true
        // })
        Alert.alert(
            "Cancel Order",
            "Are you sure you want to cancel the order ?",
            [
                {
                    text: 'No',
                    onPress: () => console.log('Cancel Delete Item'),
                    style: 'cancel',
                },
                {
                    text: 'Yes', onPress: () => this.handleOrderCancel()
                },
            ],
            { cancelable: false },
        )
    }

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

    handleOrderCancel() {

        let params = {
            session_id: this.props.session_id,
            transaction_id: this.props.route.params.idTrans,
            reason: "Cancelled By User"
        }
        // console.log(params)
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/transaction/cancel', params).then(res => {
            let respon = res.data.status
            Alert.alert(respon, 'Order was canceled')
            this.props.navigation.navigate('Home', { screen: 'ORDER' });
        }).catch(error => {
            let response = error.response.data;
            Alert.alert('', response.msg);
        })
        this.setState({
            modalVisible: false
        })

    }

    getDetailTrans() {
        let params = {
            session_id: this.props.session_id,
            transaction_id: this.props.route.params.idTrans
        }
        // console.log("PARAMETER : " + JSON.stringify(params))
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/transaction/detail', params).then(res => {
            let data = res.data

            if (data.trans_status_display == 'On Queue') {
                data.trans_status_display = 'Queueing'
            } else
                if (data.trans_status_display == 'On Process') {
                    data.trans_status_display = 'Processing'
                } else
                    if (data.trans_status_display == 'Ready to Pickup') {
                        data.trans_status_display = 'Ready for Pickup'
                    } else
                        if (data.trans_status_display == 'On Delivery') {
                            data.trans_status_display = 'Delivering'
                        } else
                            if (data.trans_status_display == 'On Completed') {
                                data.trans_status_display = 'Completed'
                            } else
                                if (data.trans_status_display == 'Cancelled') {
                                    data.trans_status_display = 'Cancelled'
                                }

            // console.log(data.trans_status_display)
            // console.log("INI OUTLET "+ data.outlet)
            // console.log("OUTLET-CODE" + data.outlet_code)
            // console.log("TRANS-DISPLAY" + data.trans_type_display)

            this.setState({
                outlet: data.outlet,
                outlet_code: data.outlet_code,
                trans_status_display: data.trans_status_display,
                transaction_detail: data.transaction_detail,
                detail_trans: data,
                is_reviewed: data.is_reviewed,
                review_rating: data.review_rating,
                trans_status: data.trans_status,
                numberId: data.id.substring(0, 5).toUpperCase()

            })
        }).catch(error => {
            let response = error.response.data;
            Alert.alert(error, response.msg);
            this.setState({
                indicator: false,
            })

            // Alert.alert(response.msg);
        })
    }

    render() {
        // console.log(this.state.detail_trans)
        // console.log(this.state.detail_trans.used_reward)
        console.log(this.state.transaction_detail)
        return (
            <View style={styles.container}>
                <Modal animationType="slide"
                    transparent={true}
                    visible={this.state.modalVisible}
                    onRequestClose={() => {
                        this.setState({
                            modalVisible: false
                        })
                    }}>
                    <View style={styles.centerViewModal}>
                        <View style={styles.modalView}>
                            <Text style={{ fontSize: 12, color: '#CFB368', fontFamily: 'Gotham-Black' }}>Reason</Text>
                            <View style={{ margin: 10 }}>
                                <TextInput
                                    style={styles.textInput}
                                    onChangeText={(reason) => this.setState({ reason })}
                                    value={this.state.reason}
                                    textAlign='center'
                                />
                            </View>
                            <View>
                            </View>
                            <View style={{ margin: 5, flexDirection: 'row' }}>
                                <TouchableOpacity style={{ margin: 5 }} onPress={() => this.handleOrderCancel()}>
                                    <View style={styles.button2}>
                                        <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 16 }}>Cancel</Text>
                                    </View>
                                </TouchableOpacity>
                                <TouchableOpacity style={{ margin: 5 }} 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={styles.header}>
                    <Text style={{ fontSize: 26, fontFamily: 'Gotham-Light', textAlign: 'center', color: 'grey' }}>#{this.state.numberId}</Text>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', textAlign: 'center', color: 'grey' }}>{moment(this.state.detail_trans.trans_time).format('DD MMMM YYYY HH:mm:ss')}</Text>
                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', textAlign: 'center', color: 'grey' }}>{this.state.detail_trans.trans_status_display}</Text>
                </View>
                <ScrollView style={styles.body}>

                    <View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 1, borderColor: 'grey', marginHorizontal: 10, padding: 10 }}>
                        <View style={{ flex: 0.1, justifyContent: 'center' }}>
                            <FontAwesome name="map-marker" size={24} color="#d34343" />
                        </View>
                        {
                            this.state.detail_trans.trans_type_display == 'Pick Up' ? (
                                <View style={{ flex: 0.6, justifyContent: 'center' }}>
                                    <Text style={{ fontSize: 14, fontFamily: 'Gotham-Black', color: 'grey' }}>{this.state.detail_trans.outlet}</Text>
                                    <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{this.state.detail_trans.outlet_address}</Text>
                                </View>
                            ) : (
                                    <View style={{ flex: 0.6, justifyContent: 'center' }}>
                                        <Text style={{ fontSize: 14, fontFamily: 'Gotham-Black', color: 'grey' }}>{this.state.detail_trans.recipient_address_name}</Text>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{this.state.detail_trans.recipient_address}</Text>
                                    </View>

                                )
                        }
                        {
                            this.state.detail_trans.trans_type_display == 'Pick Up' ? (
                                <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={{ marginLeft: 10, marginTop: 10, paddingLeft: 10 }}>
                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>PESANAN</Text>
                    </View>
                    {
                        this.state.transaction_detail.map((item, index) => {
                            // total = total + item.quantity * item.price
                            return (
                                <View style={{ margin: 0 }} key={index} >
                                    {
                                        item.item_code == 'GRAB-DELIVERY' ? (
                                            null
                                        ) : (
                                                <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-around', marginHorizontal: 10, marginVertical: 5 }}>
                                                    <View style={{ flex: 0.1, alignItems: 'center', justifyContent: 'center', alignItems: 'center', marginLeft: 18 }}>
                                                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light' }}>{item.item_quantity}</Text> */}
                                                        <NumberFormat decimalScale={0} value={item.item_quantity} renderText={value => <Text style={{ fontSize: 20, fontFamily: 'Gotham-Light', color: '#838383' }}>{value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                                    </View>
                                                    <View style={{ flex: 0.2, alignItems: 'center' }}>
                                                        <Image source={{ uri: item.item_image }} style={{ height: 50, width: 50, borderRadius: 5 }}></Image>
                                                    </View>
                                                    <View style={{ flex: 0.4, alignItems: 'baseline', justifyContent: 'center', alignItems: 'flex-start', paddingLeft: 10 }}>
                                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{item.item_name} </Text>
                                                        
                                                        {
                                                            item.item_note == '' ? (
                                                                null
                                                            ) : (
                                                                    <Text style={{ fontSize: 10, fontFamily: 'Gotham-Light', color: '#838383'}}>Keterangan : {item.item_note} </Text>
                                                                )
                                                        }

                                                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', top: 10 }}>Keterangan : {item.item_note} </Text> */}
                                                    </View>
                                                    <View style={{ flex: 0.3, alignItems: 'flex-end', justifyContent: 'center', paddingRight: 10 }}>
                                                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light' }}>{item.item_quantity * item.item_price} </Text> */}
                                                        <NumberFormat decimalScale={0} value={item.item_quantity * item.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.state.detail_trans != '' ? (
                            this.state.detail_trans.used_reward.length ? (
                                <>
                                    <View style={{ borderTopWidth: 1, borderColor: 'grey', marginHorizontal: 10, marginTop: 5 }}>
                                        <View style={{ paddingLeft: 10, paddingTop: 10 }}>
                                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>VOUCHER</Text>
                                        </View>
                                    </View>
                                    <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: 10 }}>
                                        <View style={{ flex: 0.5, marginLeft: 20, marginVertical: 5 }}>
                                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>{this.state.detail_trans.used_reward[0].reward.title}</Text>
                                        </View>
                                        <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                                            <TouchableOpacity onPress={() => this.props.navigation.navigate('Reward Detail', { rewardId: this.state.detail_trans.used_reward[0].id })}>
                                                <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: '#CFB368' }}>View Detail</Text>
                                            </TouchableOpacity>
                                            {/* <NumberFormat decimalScale={0} value={this.state.detail_trans.point_reduce} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} /> */}
                                        </View>
                                    </View>
                                </>
                            ) : (null)
                        ) : (null)
                    }
                    <View style={{ borderTopWidth: 1, borderColor: 'grey', marginHorizontal: 10, marginTop: 5 }}>
                        <View style={{ paddingLeft: 10, paddingTop: 10 }}>
                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>PAYMENT</Text>
                        </View>
                    </View>
                    <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: 10 }}>
                        <View style={{ flex: 0.5, marginLeft: 20, marginVertical: 5 }}>
                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Balance Used</Text>
                        </View>
                        <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                            {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light' }}>{this.state.detail_trans.trans_paid}</Text> */}
                            <NumberFormat decimalScale={0} value={this.state.detail_trans.point_reduce} 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', marginHorizontal: 10 }}>
                        <View style={{ flex: 0.5, marginLeft: 20, marginVertical: 5 }}>
                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Point Used</Text>
                        </View>
                        <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                            {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light' }}>{this.state.detail_trans.point_booked}</Text> */}
                            <NumberFormat decimalScale={0} value={this.state.detail_trans.point_booked} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                        </View>
                    </View>
                    <View style={{ marginTop: 5, borderTopWidth: 1, borderColor: 'grey', marginHorizontal: 10, flexDirection: 'row', justifyContent: 'space-between', flex: 1 }}>
                        <View style={{ flex: 0.5, marginLeft: 10, marginVertical: 5 }}>
                            <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Harga</Text>
                        </View>
                        <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                            {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', textAlign: 'right' }}>{this.state.detail_trans.trans_subtotal}</Text> */}
                            <NumberFormat decimalScale={0} value={this.state.detail_trans.trans_subtotal} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', textAlign: 'right' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                        </View>
                    </View>
                    {
                        this.state.detail_trans != '' ? (
                            this.state.detail_trans.used_reward.length ? (
                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', flex: 1, marginHorizontal: 10 }}>
                                    <View style={{ flex: 0.5, marginLeft: 10, marginVertical: 5 }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Voucher</Text>
                                    </View>
                                    <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                                        {/* <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', textAlign: 'right' }}>- {this.state.detail_trans.trans_discount}</Text> */}
                                        <NumberFormat decimalScale={0} value={this.state.detail_trans.used_reward[0].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>
                            ) : (null)
                        ) : (null)
                    }
                    {
                        this.state.detail_trans != '' ? (
                            this.state.detail_trans.trans_type == 2 ? (
                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', flex: 1, marginHorizontal: 10 }}>
                                    <View style={{ flex: 0.5, marginLeft: 10, marginVertical: 5 }}>
                                        <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey' }}>Ongkis kirim</Text>
                                    </View>
                                    <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                                        {
                                            this.state.detail_trans.transaction_detail.map((item, index) => {
                                                // console.log(item)
                                                if (item.item_code == 'GRAB-DELIVERY') {
                                                    return (
                                                        <NumberFormat decimalScale={0} value={item.item_price} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', textAlign: 'right' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                                    )
                                                }
                                            })
                                        }
                                        {/* <NumberFormat decimalScale={0} value={this.state.detail_trans.trans_discount} renderText={value => <Text style={{ fontSize: 12, fontFamily: 'Gotham-Light', color: 'grey', textAlign: 'right' }}>- Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} /> */}
                                    </View>
                                </View>
                            ) : (null)
                        ) : (null)
                    }
                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', flex: 1, marginHorizontal: 10, marginTop: 5 }}>
                        <View style={{ flex: 0.5, marginLeft: 10, marginVertical: 5 }}>
                            <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', color: '#CFB368' }}>Total</Text>
                        </View>
                        <View style={{ flex: 0.5, marginVertical: 5, alignItems: 'flex-end', marginRight: 10 }}>
                            {/* <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', textAlign: 'right', color: '#CFB368' }}>{this.state.detail_trans.trans_total}</Text> */}
                            <NumberFormat decimalScale={0} value={this.state.detail_trans.point_reduce} renderText={value => <Text style={{ fontSize: 20, fontFamily: 'Gotham-Black', textAlign: 'right', color: '#CFB368' }}>Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                        </View>
                    </View>
                    {
                        this.state.trans_status == 0 ? (<TouchableOpacity onPress={() => this.handleCancel()}>
                            <View style={styles.button}>
                                <Text style={{ color: 'white', fontSize: 16, fontFamily: 'Gotham-Black' }}>Cancel</Text>
                            </View>
                        </TouchableOpacity>) : (null)
                    }

                    {
                        this.state.trans_status == 4 ? (
                            this.state.is_reviewed ? (

                                <View style={{ height: 70, borderWidth: 1, borderRadius: 10, justifyContent: 'center', margin: 30, borderColor: '#CFB368' }}>
                                    <Text style={{ fontFamily: 'Gotham-Light', color: '#838383', fontSize: 16, textAlign: 'center', paddingHorizontal: 5 }}> You Rated </Text>
                                    <Rating imageSize={20} style={{ top: 5 }} readonly startingValue={this.state.review_rating} ratingBackgroundColor='#CFB368' />
                                </View>

                            ) : (
                                    <TouchableOpacity style={{ justifyContent: 'center' }} onPress={() => this.props.navigation.navigate('RatingOrder', { idTrans: this.state.detail_trans.id })}>
                                        <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', justifyContent: 'center', marginRight: 20, marginLeft: 20, marginTop: 50 }}>
                                            <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', paddingHorizontal: 5 }}>Rate Order</Text>
                                        </View>
                                    </TouchableOpacity>
                                )

                        ) : (
                                null
                            )
                    }

                    <View style={{ marginVertical: 20 }} />
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    header: {
        justifyContent: 'center',
        flex: 0.1,
        borderBottomWidth: 1,
        borderColor: '#838383',
        marginHorizontal: 10,
        padding: 10
    },

    body: {
        flex: 0.8,
        margin: 0,
    },
    list_detail_order: {
        flex: 1,
        margin: 20,
        borderWidth: 1,
    },
    button: {
        backgroundColor: '#d34343',
        height: 40,
        marginTop: 25,
        marginHorizontal: 20,
        borderRadius: 10,
        paddingVertical: 5,
        alignItems: 'center',
        justifyContent: 'center'
    },
    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,
        trans_id: state.trans_id,
        lat: state.lat,
        long: state.long,

    }
}

export default connect(mapStateToProps)(OrderDetail);