import React from 'react';
import { View, Text, TextInput, StyleSheet, Button, TouchableOpacity, ScrollView, FlatList, Image } from 'react-native';
import { connect } from 'react-redux'
// import { CheckBox } from 'react-native-elements'
import CheckBox from 'react-native-check-box'
import { Card } from 'react-native-shadow-cards'
import { Entypo, Ionicons, MaterialCommunityIcons, MaterialIcons, AntDesign, FontAwesome } from '@expo/vector-icons'
import i18n from 'i18n-js';
import CurrencyFormat from 'react-currency-format';
import ItemShoping from './ItemShopingCart';
import Axios from 'axios'
import ActionType from '../redux/globalActionType';
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['VirtualizedLists should never be nested']);

class ShoppingCart extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            kasproBalance: '',
            kasproPoint: '',
            checkedBalance: false,
            checkedPoint: false,
            checkedBalancePoint: false,
            balanceused: 0,
            pointsused: 0,
            ongkir: 0,
            diskon: 0,
            isDelivery: false,
            isPickUp: false,
            order_item: this.props.order_item,
            grabtype: '',
            grabamount: '',
            grabpickup: '',
            grabdropoff: '',
            grabdestination: '',
            // dummyBalance : 155000,
            // dummyPoint : 20000
        }
    }


    checkChangeTrans(val) {
        console.log('hai lg di sini')
        console.log(val)
        if (val == 'delivery') {
            this.setState({
                isDelivery: true,
                isPickUp: false
            })
            console.log('ini delivery')
        } else {
            this.setState({
                isPickUp: true,
                isDelivery: false
            })
            console.log('ini pickup')
        }
    }

    handleMin(item, index) {
        const list_order_item = this.props.order_item;

        let is_xist = list_order_item.find(row => row.id == item.id)
        if (is_xist) {
            if (is_xist.quantity != 0) {
                const order_item = {
                    id: item.id,
                    name: item.name,
                    price: item.price,

                }
                this.props.reduceQuantityItem(order_item)

                let quantity = 0
                for (let i = 0; i < list_order_item.length; i++) {
                    const row = list_order_item[i];
                    const qty = list_order_item[i];
                    if (row.id == item.id) {
                        quantity = row.quantity
                    }
                    const listMenu = [...this.state.listMenu]
                    listMenu[index].qty = quantity
                    this.setState({
                        listMenu
                    })
                }
            } else if (is_xist.quantity == 0) {
                const order_item = {
                    id: item.id,
                    name: item.name,
                    price: item.price,

                }
                this.props.removeFromChart(order_item)
            }
        }
    }

    handleAdd(item, index) {

        const order_item = {
            id: item.id,
            code: item.code,
            name: item.name,
            description: item.description,
            note: 'jangan garing',
            price: parseInt(item.price),
        }

        this.props.addToChart(order_item)

        const list_order_item = this.props.order_item;
        let is_xist = list_order_item.find(row => row.id == item.id)

        let quantity = 0
        if (is_xist) {
            quantity = is_xist.quantity
        }

        const listMenu = [...this.state.listMenu]
        listMenu[index].qty = quantity
        this.setState({
            listMenu
        })
    }

    checkedSelection(val) {
        // console.log(val)
        if (val == 'balance') {
            this.setState({
                checkedBalance: true,
                checkedPoint: false,
                checkedBalancePoint: false,
                balanceused: this.props.order_total,
                pointsused: 0
            })
        } else if (val == 'point') {
            this.setState({
                checkedBalance: false,
                checkedPoint: true,
                checkedBalancePoint: false,
                pointsused: this.props.order_total,
                balanceused: 0
            })
        } else {
            this.setState({
                checkedBalance: false,
                checkedPoint: false,
                checkedBalancePoint: true,
                // balanceused : this.props.order_total - this.state.dummyPoint,
                // pointsused : this.props.order_total,
            })
            if (this.state.kasproPoint - this.props.order_total >= -1) {
                this.setState({
                    pointsused: this.props.order_total
                })
            } else {
                this.setState({
                    balanceused: this.props.order_total - this.state.kasproPoint,
                    pointsused: this.state.kasproPoint
                })
            }




        }
    }

    componentDidMount() {

        this.getMenuList()
        this.getBalance()
        this.getRate()
    }

    getMenuList() {
        let params = {

            outlet_id: "dec1abbb-95d0-46ae-a6cd-2bf306590f15"
        }
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/menu/get_list', params).then(res => {

            let data = res.data.data
            this.setState({
                listCategory: data.category,
                listMenu: data.menu
            })

            let last_category = ''
            let list_menu = []

            for (let i = 0; i < data.menu.length; i++) {

                const row = data.menu[i];

                // cari sudah ada belum di redux
                let is_xist = this.props.order_item.find(item => row.id == item.id)
                if (is_xist) {
                    row['qty'] = is_xist.quantity
                } else {
                    row['qty'] = 0
                }

                if (last_category != row.category.name) {
                    let category = {
                        "id": row.category.id,
                        "name": row.category.name,
                        "code": "CATEGORY"
                    }
                    list_menu.push(category)
                    list_menu.push(row)
                    last_category = row.category.name
                } else {
                    list_menu.push(row)
                }
            }
            this.setState({
                listMenu: list_menu
            })

        })

    }

    getRate() {

        let params = {

            session_id: this.props.session_id,
            outlet_id: '0cb81ffe0c8242bea42d39c9b92ccaac',
            address_id: '6263e6cb70634d5da523345a2cdbc071',
            order_item: this.props.order_item
        }

        console.log("INI PARAMETER : " + JSON.stringify(params));

        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/delivery/rate', params).then(res => {
            console.log("INI LHO CUY : " + JSON.stringify(res.data.data.destination.address))

            this.setState({
                grabtype: res.data.data.quotes[0].service.type,
                grabamount: res.data.data.quotes[0].amount,
                grabpickup: res.data.data.quotes[0].estimatedTimeline.pickup,
                grabdropoff: res.data.data.quotes[0].estimatedTimeline.dropoff,
                grabdestination: res.data.data.destination.address,

            })

            let setGrabProps = {
                grabtype: this.state.grabtype,
                grabamount: this.state.grabamount,
                grabpickup: this.state.grabpickup,
                grabdropoff: this.state.grabdropoff,
                grabdestination: this.state.grabdestination,
            }

            this.props.setGrab(setGrabProps);

            let setOrdersProps = {
                balanceUsed: this.state.balanceused,
                pointused: this.state.pointsused, 
            }
            this.props.setOrder(setOrdersProps);


        }).catch(error => {
            console.log('ini error ' + error)
        })
    }

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

        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/get_profile', params).then(res => {
            // console.log(res.data)
            const { kaspro_balance, kaspro_point } = res.data
            // console.log(kaspro_balance,kaspro_point)
            this.setState({
                kasproBalance: kaspro_balance,
                kasproPoint: kaspro_point
            })

            // console.log(this.state.kasproBalance, this.state.kasproPoint)
        }).catch(error => {
            console.log('ini error ' + error)
        })
    }

    render() {
        return (
            <ScrollView style={styles.container}>
                <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                    <TouchableOpacity style={styles.buttonDelivery} onPress={() => this.checkChangeTrans('delivery')}>
                        <Text style={{ textAlign: 'center', color: '#354175', fontWeight: 'bold' }}>{i18n.t('delivery')}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.buttonPickup} onPress={() => this.checkChangeTrans('pickup')}>
                        <Text style={{ textAlign: 'center', color: '#fff', fontWeight: 'bold' }}>{i18n.t('pickup')}</Text>
                    </TouchableOpacity>
                </View>
                <View style={{ alignItems: 'center' }}>
                    {
                        this.state.isDelivery == true ? (
                            <Card style={{ margin: 5, padding: 10 }}>
                                <Text style={{ textAlign: 'center' }}> Ambil pesanan kamu di</Text>
                                <Text style={{ textAlign: 'center' }}>{this.props.address}</Text>
                            </Card>

                        ) : (
                                <Card style={{ margin: 5, padding: 10 }}>
                                    <Text style={{ textAlign: 'center' }}> Pesanan kamu dikirim ke</Text>
                                    <Text style={{ textAlign: 'center' }}>{this.props.address}</Text>
                                </Card>
                            )
                    }
                </View>
                <View style={styles.header}>
                    <Text style={{ textAlign: 'center', fontSize: 15 }}>YOUR ORDER(S)</Text>
                    <TouchableOpacity onPress={() => this.props.navigation.goBack()}>
                        <Text style={{ textAlign: 'center', fontSize: 15, color: '#ccb46c' }}>+ ADD MORE</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.order}>
                    <FlatList
                        data={this.state.order_item}
                        renderItem={({ item, index }) => (
                            <ItemShoping navigation={this.props.navigation}
                                item={item}
                                handleAdd={() => this.handleAdd(item, index)}
                                handleMin={() => this.handleMin(item, index)}
                            />
                        )}
                        keyExtractor={item => item.id}
                    />
                </View>
                <View style={styles.voucher}>
                    <TouchableOpacity>
                        <Text style={{ color: '#ccb46c' }}>+ ADD VOUCHER</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.payment}>
                    <Text>PAYMENT METHODS</Text>
                </View>
                <View style={{ alignItems: 'center' }}>
                    {
                        this.state.kasproBalance < this.props.order_total ? (
                            <Card style={{ margin: 5, padding: 10, backgroundColor: 'gray' }}>
                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <View>
                                        <Text>EXCELSO BALANCE</Text>
                                    </View>
                                    <View style={{ paddingRight: 10 }}>
                                        <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>EXCELSO BALANCE</Text>
                                            </View>
                                            <View style={{ paddingRight: 10 }}>
                                                <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.kasproPoint < this.props.order_total ? (
                            <Card style={{ margin: 5, padding: 10, backgroundColor: 'gray' }}>
                                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <View>
                                        <Text>EXCELSO POINTS</Text>
                                    </View>
                                    <View style={{ paddingRight: 10 }}>
                                        <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>EXCELSO POINTS</Text>
                                            </View>
                                            <View style={{ paddingRight: 10 }}>
                                                <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.kasproPoint + this.state.kasproBalance >= this.props.order_total && this.state.kasproBalance != 0 && this.state.kasproPoint != 0 ? (
                            <TouchableOpacity onPress={() => {
                                this.checkedSelection('balancepoint')
                            }}>
                                <Card style={{ margin: 5, padding: 10 }}>
                                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <View>
                                            <Text>EXCELSO BALANCE + POINTS</Text>
                                        </View>
                                        <View style={{ paddingRight: 10 }}>
                                            <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>
                        ) : (
                                <Card style={{ margin: 5, padding: 10, backgroundColor: 'gray' }}>
                                    <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <View>
                                            <Text>EXCELSO BALANCE + POINTS</Text>
                                        </View>
                                        <View style={{ paddingRight: 10 }}>
                                            <FontAwesome name='circle-o' size={30} color={'#ccb46c'} />
                                        </View>
                                    </View>
                                </Card>

                            )
                    }
                </View>
                <View style={{ alignItems: 'center', }}>
                    <Card style={{ margin: 5, padding: 10 }}>
                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginBottom: 5 }}>
                            <View>
                                <Text>Your Balance</Text>
                                <Text>Your Points</Text>
                            </View>
                            <View style={{ paddingRight: 30, alignItems: 'flex-end' }}>
                                <Text>{this.state.kasproBalance}</Text>
                                <Text>{this.state.kasproPoint}</Text>
                            </View>
                        </View>
                        <View style={{ flexDirection: 'row', justifyContent: 'space-between', borderTopWidth: 1 }}>
                            <View style={{ marginTop: 5 }}>
                                <Text>Your Balance Used</Text>
                                <Text>Your Points Used</Text>
                            </View>
                            <View style={{ paddingRight: 30, marginTop: 5, alignItems: 'flex-end' }}>
                                <Text>- {this.state.balanceused}</Text>
                                <Text>- {this.state.pointsused}</Text>
                            </View>
                        </View>
                    </Card>
                </View>

                <View style={styles.paymentDetails}>
                    <Text>PAYMENT DETAILS</Text>
                </View>
                <View style={{ margin: 10 }}>
                    {/* <Text style={{ paddingLeft: 20, paddingTop: 15, color: 'gray' }}>Detail Pembayaran</Text> */}
                    <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: 'space-between' }}>
                        <View>
                            <Text style={{ paddingLeft: 20, paddingTop: 15, color: 'gray' }}>Harga</Text>
                        </View>
                        <View style={{ paddingRight: 30, paddingTop: 10, alignItems: 'flex-end' }}>
                            <Text style={{ color: 'gray' }}>{this.props.order_total}</Text>
                        </View>
                    </View>
                    <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: 'space-between' }}>
                        <View>
                            <Text style={{ paddingLeft: 20, paddingTop: 10, color: 'gray' }}>Ongkos Kirim</Text>
                        </View>
                        <View style={{ paddingRight: 30, paddingTop: 10, alignItems: 'flex-end' }}>
                            <Text style={{ color: 'gray' }}>{this.props.grabamount}</Text>
                        </View>
                    </View>
                    <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: 'space-between' }}>
                        <View>
                            <Text style={{ paddingLeft: 20, paddingTop: 10, color: 'gray' }}>Diskon</Text>
                        </View>
                        <View style={{ paddingRight: 30, paddingTop: 10, alignItems: 'flex-end' }}>
                            <Text style={{ color: 'gray' }}>{this.state.diskon}</Text>
                        </View>
                    </View>
                    <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: 'space-between' }}>
                        <View style={{ marginTop: 15, paddingLeft: 20, paddingTop: 10 }}>
                            <Text style={{ fontSize: 35, color: '#ccb46c' }}>Total</Text>
                        </View>
                        <View style={{ marginTop: 15, paddingRight: 30, paddingTop: 10, alignItems: 'flex-end' }}>
                            <Text style={{ fontSize: 35, color: '#ccb46c' }}>{this.props.order_total}</Text>
                        </View>
                    </View>
                    <View style={{ flexDirection: 'row', marginTop: 10, justifyContent: 'space-between' }}>
                        <View>
                            <Text style={{ paddingLeft: 20, paddingTop: 10, color: 'gray' }}>Tujuan</Text>
                        </View>
                        <View style={{ paddingRight: 30, paddingTop: 10, alignItems: 'flex-end' }}>
                            <Text style={{ color: '#ccb46c' }}>{this.props.address}</Text>
                        </View>
                    </View>
                    <View style={{ margin: 20, }}>
                        <Button title='Checkout' color='#ccb46c' onPress={() => this.props.navigation.navigate('Confirm Your Order', { balanceUsed: this.state.balanceused, pointused: this.state.pointsused })} />
                    </View>
                </View>
            </ScrollView>
        )
    }
}


const styles = StyleSheet.create({

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

    header: {
        flex: 0.2,
        margin: 10,
        padding: 20,
        borderBottomWidth: 1,
        borderTopWidth: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },

    order: {
        flex: 1,
        margin: 10,
        backgroundColor: '#fff'
    },

    payment: {
        flex: 1,
        margin: 10,
        padding: 20,
        borderTopWidth: 1,
        borderBottomWidth: 1,
        // backgroundColor: 'lightblue'
    },

    voucher: {
        flex: 1,
        margin: 10,
        padding: 20,
        borderTopWidth: 1,
        borderBottomWidth: 1,
        // backgroundColor: 'lightblue'
    },

    paymentDetails: {
        flex: 1,
        margin: 10,
        padding: 20,
        borderTopWidth: 1,
        borderBottomWidth: 1,
        // backgroundColor: 'lightblue'
    },
    buttonDelivery: {
        marginTop: 10,
        paddingTop: 15,
        paddingBottom: 15,
        marginRight: 0,
        marginLeft: 0,
        backgroundColor: '#cce8f0',
        borderRadius: 10,
        borderWidth: 0,
        borderColor: '#fff',
        width: '50%',
        // top: -20,
    },
    buttonPickup: {
        marginTop: 10,
        paddingTop: 15,
        paddingBottom: 15,
        marginRight: 0,
        marginLeft: -50,
        backgroundColor: '#354175',
        borderRadius: 10,
        borderWidth: 0,
        borderColor: '#fff',
        width: '40%',
        // top: -20,
    },

    shadowEdit: {
        height: 30,
        width: 25,
        borderWidth: 1,
        borderRadius: 2,
        borderColor: '#ddd',
        borderBottomWidth: 0,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 2,
        elevation: 1,
        marginLeft: 5,
        marginRight: 5,
        marginTop: 10,
    },
    shadowAdd: {
        height: 30,
        width: 75,
        borderWidth: 1,
        borderRadius: 2,
        borderColor: '#ddd',
        borderBottomWidth: 0,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 2,
        elevation: 1,
        marginLeft: 5,
        marginRight: 5,
        marginTop: 10,
        flexDirection: 'row'
    },
    shadowMin: {
        height: 20,
        width: 20,
        borderWidth: 1,
        borderRadius: 2,
        borderColor: '#ddd',
        borderBottomWidth: 0,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.8,
        shadowRadius: 2,
        elevation: 1,
        marginLeft: 5,
        marginRight: 5,
        marginTop: 10,
    }


})


const mapDispatchToProps = (dispacth) => {
    return {

        addToChart: (item) => dispacth({
            type: ActionType.ADD_TO_CHART,
            data: {
                item: item
            }
        }),
        //REDUCE QUANTITY ITEM
        reduceQuantityItem: (item) => dispacth({
            type: ActionType.REDUCE_QUANTITY_ITEM,
            data: {
                item: item
            }
        }),
        removeFromChart: (item) => dispacth({
            type: ActionType.REMOVE_FROM_CHART,
            data: {
                item: item
            }
        }),

        setGrab: (setGrabProps) => dispacth({
            type: ActionType.SET_GRAB,
            data: {
                grabtype:  setGrabProps.grabtype,
                grabamount: setGrabProps.grabamount,
                grabpickup: setGrabProps.grabpickup,
                grabdropoff: setGrabProps.grabdropoff,
                grabdestination: setGrabProps.grabdestination,
            }
        }),
        setOrder: (setOrdersProps) => dispacth({
            type: ActionType.SET_ORDERS,
            data: {
                balanceUsed: setOrdersProps.balanceUsed,
                pointused: setOrdersProps.pointsused,
            }
        }),
    }
}

const mapStateToProps = (state) => {
    return {
        session_id: state.session_id,
        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,
        addressId: state.addressId
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(ShoppingCart)
