import { EvilIcons, Ionicons, MaterialCommunityIcons, SimpleLineIcons } from '@expo/vector-icons';
import Axios from 'axios';
import i18n from 'i18n-js';
import React from 'react';
import { ActivityIndicator, Alert, FlatList, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';
import { CheckBox } from 'react-native-elements';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';
import MyStatusBar from './MyStatusBar';

// import ravLog from '../helper/debug';

class DeliveryAddrees extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            address_name: [],
            data: [],
            data_before_search: [],
            search: '',
            indicator: true,
            caretHidden: true
            // outlet_id: '',
            // grabamount: ''
        }
    }

    componentDidMount() {
        this._unsubscribe = this.props.navigation.addListener('focus', () => {
            this.setState({
                indicator: true
            })
            this.getAddreess()
        });
        this.setState({
            indicator: true
        })
        this.getAddreess()
    }

    componentWillUnmount() {
        this._unsubscribe();
    }

    onChangeAddress = data => {
        // console.log('DATA FROM CHANGE PROFILE  ' + data);
        this.getAddreess()
    }

    getAddreess() {
        let params = {
            session_id: this.props.session_id,
        }
        Axios.post(this.props.BASE_URL + 'crm/v2/member/get_address', params).then(res => {
            const dataAlamat = res.data.data;
            console.log("INI DATA :" + JSON.stringify(dataAlamat))
            let address = []
            for (let i = 0; i < dataAlamat.length; i++) {
                const element = dataAlamat[i];
                address.push(element)

            }
            this.setState({
                data: address,
                data_before_search: dataAlamat,
                indicator: false
            })

            let data_alamat = []
            this.state.data.map(item => {
                let b = item.name
                data_alamat.push(b)
            })


        }).catch(error => {
            let response = error.response.data;
            Alert.alert(
                '',
                response.msg
            )
        })
    }



    getRate(address_id) {

        // console.log('ADdress id : ' + address_id)
        let params = {
            session_id: this.props.session_id,
            address_id: address_id,
        }

        // console.log("INI PRAMETER NYA : " + JSON.stringify(params))

        Axios.post(this.props.BASE_URL + 'crm/v2/delivery/rate', params).then(res => {

            // this.setState({
            //     grabamount: res.data.data.amount,
            //     grabdestination: res.data.data.outlet_name,
            // })

            let setGrabProps = {
                // grabdestination: this.state.grabdestination,
                // grabamount: this.state.grabamount,
                grabamount: res.data.data.amount
            }


            let OutletChange = {
                outlet_id: res.data.data.outlet_id,
                name_outlet: res.data.data.outlet_name,
            }

            this.props.setGrab(setGrabProps);

            this.props.setChangeOutletProps(OutletChange);
            // console.log("INI SUKSES RESPONNYA ")
            // console.log('Delivery Amount Address : ' +  res.data.data.amount)


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


        }).catch(error => {
            let response = error.response.data;
            Alert.alert('', response.msg);
        })
    }

    addAdreess() {
        this.props.navigation.navigate('Address Detail', { 'data': 'sample', onChangeAddress: this.onChangeAddress })
    }


    filterData(text) {
        const newData = this.state.data_before_search.filter(function (item) {
            const itemData = item.name ? item.name.toUpperCase() : ''.toUpperCase();
            const textData = text.toUpperCase();
            return itemData.indexOf(textData) > -1;
        });

        if (text === '') {
            this.setState({
                data: this.state.data_before_search,
                search: ''
            })
        } else {
            this.setState({
                data: newData,
                search: text
            });
        }
    }


    onSave(address, id, name) {

        let setDataAddress = {
            address: address,
            addressId: id,
            home_address: name
        }

        this.props.setAddress(setDataAddress);

        let params = {
            session_id: this.props.session_id,
            address_id: id,
        }

        Axios.post(this.props.BASE_URL + 'crm/v2/delivery/rate', params).then(res => {

            let setGrabProps = {
                grabamount: res.data.data.amount
            }


            let OutletChange = {
                outlet_id: res.data.data.outlet_id,
                name_outlet: res.data.data.outlet_name,
            }

            this.props.setGrab(setGrabProps);
            this.props.setChangeOutletProps(OutletChange);
            this.props.setTypePickup(false)

            if (this.props.route.params.from == 'shoppingCart') {
                this.props.navigation.navigate('Shopping Cart', { outlet_change: true, outlet_id: res.data.data.outlet_id })
            } else {
                this.props.navigation.navigate('Home', {
                    screen: 'MENU',
                    params: { user: 'janeT' },
                });
            }

            if (this.props.value_voucher !== "") {
                if (this.props.value_voucher.reward.type == 'percentage') {
                    this.handleVoucherSelect()
                }
            }

        }).catch(error => {
            let response = error.response.data;
            console.log('ini error ' + response.msg)
            Alert.alert('', response.msg)
        })


        // let recalculateProps = {
        //     order_total: 0,
        //     order_quantity:0,
        //     order_item:[]
        // }
        // this.props.setRecalculate(recalculateProps)

        // Alert.alert(
        //     '',
        //     'Apakah anda akan memilih alamat untuk pengiriman ?',
        //     [

        //       {text: 'OK', onPress: () => this.props.navigation.navigate("Menu Select") },
        //     ],
        //     { cancelable: false }
        //   )

    }

    deleteAddress(id) {
        let params = {
            session_id: this.props.session_id,
            address_id: id,
        }
        Axios.post(this.props.BASE_URL + 'crm/v2/member/delete_address', params).then(res => {
            this.componentDidMount()
        }).catch(error => {
            let response = error.response.data;
            Alert.alert('', response.msg)
        })
    }

    handleVoucherSelect() {
        //SPINNER ON 
        this.setState({
            spinner: true,
        })
        //CEK TYPE TRANSAKSINYA DELIVERY OR PICKUP, DICEK UNTUK DI MASUKAN DI PARAMATER PEMANGGILAN API
        let type_trans = ""
        if (this.props.type_pickup == true) {
            type_trans = 'Pickup'
        } else {
            type_trans = 'Delivery'
        }

        let params = {
            session_id: this.props.session_id,
            trans_type: type_trans,
            order_item: this.props.order_item,
            reward_id: this.props.voucher.id,
            delivery_charge: this.props.grabamount,
        }

        // MULAI DISINI PEMANGGILAN API DI MULAI, KALAU BERHASIL SET VALUE VOUCHER NYA DAN SPINER DIMATIKAN, KALAU GAGAL CABUT SESSION VOUCHER DAN SPINNER DI MATIKAN
        Axios.post(this.props.BASE_URL + 'crm/v2/reward/get_value', params).then(res => {
            let voucherProps = {
                value_voucher: res.data.reward,
                voucher: res.data.reward
            }
            this.props.setVoucher(voucherProps);
            this.setState({
                spinner: false,
            })
        }).catch(error => {
            try {
                let response = error.response.data
                Alert.alert("", response.msg)
                this.setState({
                    spinner: false,
                })
                // FUNGSI REDUX UNTUK HAPUS VOUCHER
                this.props.removeVoucher()
            } catch (error) {
                Alert.alert("Error : ", error.toString())
                this.setState({
                    spinner: false,
                })
            }
        })
    }


    handleDeleteAddress(id) {
        Alert.alert(
            "",
            i18n.t('alertdeleteaddress'),
            [
                {
                    text: i18n.t('alertno'),
                    onPress: () => console.log("Cancel Pressed"),
                    style: "cancel"
                },
                { text: i18n.t('alertyes'), onPress: () => this.deleteAddress(id) }
            ],
            { cancelable: false }
        );
    }

    handleEditAddress(id, name, address, description, lat, long) {
        console.log('tes')
        console.log(id)
        console.log(name)
        console.log(address)
        console.log(description || 'kosong')
        console.log(lat)
        console.log(long)
        this.props.navigation.navigate('Edit Address', { address_id: id, name: name, address: address, description: description, lat: lat, long: long })
    }

    renderItem = ({ item }) => {
        return (
            <View style={styles.list_addrees}>
                <View style={{ flexDirection: 'row', flex: 1 }}>
                    <View style={{ flex: 3 }}>
                        <TouchableOpacity style={{ flex: 1, flexDirection: 'row', margin: 5 }} onPress={() => this.onSave(item.address, item.id, item.name)}>
                            <View style={{ flex: 1.5, justifyContent: 'center' }}>
                                <View>
                                    <CheckBox
                                        checkedIcon='dot-circle-o'
                                        uncheckedIcon='circle-o'
                                        checked={this.state.checked}
                                        checkedColor="#ccb46c"
                                        uncheckedColor="#ccb46c"
                                    />
                                </View>
                                <View style={{ bottom: 10 }}>
                                    <Text style={{ textAlign: 'center', color: '#ccb46c', fontFamily: 'Gotham-Light' }}>{i18n.t('selectaddress')}</Text>
                                </View>
                            </View>
                            <View style={{ flex: 3, justifyContent: 'center' }}>
                                <View>
                                    <Text style={{ fontFamily: 'Gotham-Black', color: '#838383', fontSize: 15, margin: 1 }}>{item.name}</Text>
                                </View>
                                <Text style={{ fontFamily: 'Gotham-Light', color: '#838383', fontSize: 15 }}>{item.address}</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={{ flex: 1 }}>
                        <TouchableOpacity style={{ flex: 1, flexDirection: 'row', justifyContent: "center" }} onPress={() => this.handleEditAddress(item.id, item.name, item.address, item.description, item.lat, item.long)}>
                            <View style={{ alignSelf: "center", marginTop: 22, marginLeft: 35 }}>
                                <SimpleLineIcons name="pencil" size={25} color="#ccb46c" />
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={{ flex: 1 }}>
                        <TouchableOpacity style={{ flex: 1, flexDirection: 'row', justifyContent: "center" }} onPress={() => this.handleDeleteAddress(item.id)}>
                            <View style={{ alignSelf: "center", marginTop: 20 }}>
                                <EvilIcons name="trash" size={40} color="#ccb46c" />
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        );
    }
    render() {


        return (
            <View style={styles.container}>
                <MyStatusBar />
                <ScrollView>
                    <View style={{ height: 45, borderRadius: 10, borderColor: '#ccb46c', borderWidth: 1, flexDirection: 'row', marginTop: 15, marginLeft: 20, marginRight: 20 }}>
                        <View style={{ flex: 1, top: 5 }}>
                            <MaterialCommunityIcons name="map-marker" size={32} color="#ccb46c" />
                        </View>
                        <View style={{ flex: 6 }}>
                            <TextInput style={{ height: 45 }} placeholder={i18n.t('searchaddress')}
                                onChangeText={text => this.filterData(text)}
                                onClear={text => this.filterData('')}
                                caretHidden={this.state.caretHidden}
                                onFocus={() => this.setState({ caretHidden: false })}
                                value={this.state.search}></TextInput>
                        </View>
                        <View style={{ flex: 1, margin: 5 }}>
                            <Ionicons name="ios-search" size={32} color="#ccb46c" />
                        </View>
                    </View>
                    <View style={styles.btn_addreess}>
                        <TouchableOpacity onPress={() => this.addAdreess()}>
                            <View style={{ height: 40, borderRadius: 10, marginRight: 70, marginLeft: 70, backgroundColor: '#CFB368', justifyContent: 'center', alignContent: 'center' }}>
                                <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', color: 'white', fontSize: 16 }}> {i18n.t('addaddress')} </Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.listAddress}>
                        {this.state.indicator == true ? (
                            <ActivityIndicator size="large" color="#c9af6d" />
                        ) : (this.state.data.length ? (
                            <FlatList style={{ marginBottom: 25 }}
                                data={this.state.data}
                                renderItem={this.renderItem}
                                keyExtractor={item => item.id}
                            />
                        ) : (
                                <View style={{ margin: 20 }}>
                                    <Text style={{ fontFamily: 'Gotham-Light', textAlign: 'center', fontSize: 16 }}>{i18n.t('noAddressSaved')}</Text>
                                </View>
                            )

                            )}
                    </View>
                </ScrollView>
            </View>

        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    header: {

        flex: 0.5,
    },

    body: {
        flex: 3,
        marginTop: 10,
        marginRight: 20,
        marginLeft: 20,
        marginBottom: 20,
        borderWidth: 1,
    },

    btn_addreess: {
        margin: 10,
    },

    list_addrees: {
        flex: 1,
        top: 20,
        marginLeft: 20,
        marginRight: 20,
        marginBottom: 20,
        borderWidth: 1,
        borderColor: '#838383',
        borderRadius: 10,
    }

})

const mapStateToProps = (state) => {

    return {

        session_id: state.session_id,
        addressId: state.addressId,
        language: state.language,
        outlet_detailadress: state.outlet_detailadress,
        home_address: state.home_address,
        type_pickup: state.type_pickup,
        value_voucher: state.value_voucher,
        voucher: state.voucher,
        session_id: state.session_id,
        outlet_id: state.outlet_id,
        name_outlet: state.name_outlet,
        value_voucher: state.value_voucher,
        voucher: state.voucher,
        order_quantity: state.order_quantity,
        order_total: state.order_total,
        order_item: state.order_item,
        quantity: state.quantity,
        address: state.address,
        addressId: state.addressId,
        grabtype: state.grabtype,
        grabamount: state.grabamount,
        grabpickup: state.grabpickup,
        grabdropoff: state.grabdropoff,
        grabdestination: state.grabdestination,
        BASE_URL: state.BASE_URL


    }
}

const mapDispatchToProps = (dispacth) => {
    return {
        setChangeOutletProps: (OutletChange) => dispacth({
            type: ActionType.SET_CHANGE_OUTLET,
            data: {

                outlet_id: OutletChange.outlet_id,
                name_outlet: OutletChange.name_outlet,

            }
        }),
        setAddress: (setDataAddress) => dispacth({
            type: ActionType.SET_ADDRESS,
            data: {

                address: setDataAddress.address,
                addressId: setDataAddress.addressId,
                home_address: setDataAddress.home_address
            }
        }),

        setGrab: (setGrabProps) => dispacth({
            type: ActionType.SET_GRAB,
            data: {
                grabamount: setGrabProps.grabamount,
                // grabpickup: setGrabProps.grabpickup,
                // grabdropoff: setGrabProps.grabdropoff,
                // grabdestination: setGrabProps.grabdestination,
            }
        }),
        setRecalculate: (recalculateProps) => dispacth({
            type: ActionType.SET_RECALCULATE,
            data: {

                order_total: recalculateProps.order_total,
                order_quantity: recalculateProps.order_quantity,
                order_item: recalculateProps.order_item

            }
        }),
        setTypePickup: (type) => dispacth({
            type: ActionType.SET_TYPE,
            data: {
                type_pickup: type
            }
        }),
        removeVoucher: () => dispacth({
            type: ActionType.REMOVE_VOUCHER
        }),
        setVoucher: (voucherProps) => dispacth({
            type: ActionType.SET_VOUCHER,
            data: {

                voucher: voucherProps.voucher,
                value_voucher: voucherProps.value_voucher,

            }
        }),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(DeliveryAddrees)
