import React from 'react';
import { View, Text, StyleSheet, Button, FlatList, Alert, TextInput, Image } from 'react-native';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import { connect } from 'react-redux';
import { CheckBox, Icon } from 'react-native-elements';
import Axios from 'axios';
import ActionType from '../redux/globalActionType';
import { MaterialCommunityIcons, Ionicons } from '@expo/vector-icons';
// import ravLog from '../helper/debug';

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

    componentDidMount() {
        this.getAddreess()
        // console.log("INI ADDRESS ID  : " + this.props.addressId)
    }

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

    getAddreess() {
        let params = {
            session_id: this.props.session_id,
        }
        // console.log(params)

        Axios.post('https://excelsocrm.ravintoladev.com/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,
            })
        }).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('https://excelsocrm.ravintoladev.com/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 => {
            Alert.alert('ini error get rate ', error.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) {

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

        this.props.setAddress(setDataAddress);
        let params = {
            session_id: this.props.session_id,
            address_id: id,
        }

        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/delivery/rate', params).then(res => {

            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);
            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' },
                });
            }


        }).catch(error => {
            let response = error.response.data;
            Alert.alert(response.msg)
            console.log('ini error ' + response.msg)
            Alert.alert('ini error get rate ', error.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 }
        //   )


    }


    renderItem = ({ item }) => {
        return (
            <View style={styles.list_addrees}>
                <TouchableOpacity onPress={() => this.onSave(item.address, item.id)}>
                    <View style={{ flex: 1, flexDirection: 'row', margin: 20, }}>
                        <View style={{ flex: 1, marginBottom: 10, justifyContent: 'center' }}>
                            <CheckBox
                                center
                                checkedIcon='dot-circle-o'
                                uncheckedIcon='circle-o'
                                checked={this.state.checked}
                                checkedColor="#ccb46c"
                                uncheckedColor="#ccb46c"
                            />
                            <Text style={{ textAlign: 'center', color: '#ccb46c', fontFamily: 'Gotham-Light' }}>PILIH</Text>
                        </View>
                        <View style={{ flex: 3, justifyContent: 'center' }}>
                            <View style={{ margin: 5, }}>
                                <Text style={{ fontFamily: 'Gotham-Black', color: 'grey', fontSize: 19, marginBottom: 5 }}>{item.name}</Text>
                            </View>
                            <Text style={{ fontFamily: 'Gotham-Light', color: 'grey', fontSize: 15, marginBottom: 5 }}>{item.address}</Text>
                        </View>
                        <View style={{ flex: 1,justifyContent:'center' }}>
                            <View style={{ margin: 5, }}>
                                <Image
                                    style={{height:20,width:20,tintColor:'#ccb46c'}}
                                    source={require('../assets/ellipsis-v.png')}
                                />
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
            </View>

        );
    }
    render() {


        return (
            <View style={styles.container}>
                <View style={{ height: 45, borderRadius: 10, borderColor: '#ccb46c', borderWidth: 1, flexDirection: 'row', marginTop: 15, marginLeft: 10, marginRight: 10 }}>
                    <View style={{ flex: 1 }}>
                        <MaterialCommunityIcons name="map-marker" size={32} color="#ccb46c" />
                    </View>
                    <View style={{ flex: 6 }}>
                        <TextInput style={{ height: 45 }} placeholder="Cari Alamat"
                            onChangeText={text => this.filterData(text)}
                            onClear={text => this.filterData('')}
                            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: 15, marginRight: 70, marginLeft: 70, backgroundColor: '#CFB368', justifyContent: 'center', alignContent: 'center' }}>
                            <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', color: 'white', fontSize: 20 }}> +  Tambah Alamat </Text>
                        </View>
                    </TouchableOpacity>

                </View>
                <View style={styles.listAddress}>
                    <FlatList
                        data={this.state.data}
                        renderItem={this.renderItem}
                        keyExtractor={item => item.id}
                    />
                </View>
            </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,
        margin: 20,
        borderWidth: 1,
        borderColor: 'grey',
        borderRadius: 10,

    }

})

const mapStateToProps = (state) => {

    return {

        session_id: state.session_id,
        addressId: state.addressId

    }
}

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
            }
        }),

        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
            }
        }),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(DeliveryAddrees)




{/* <TouchableOpacity onPress={() => this.onSave(item.address, item.id)}>
                    <View style={{ margin: 5, }}>
                        <Text style={{ fontWeight: 'bold', fontSize: 20 }}>{item.name}</Text>
                    </View>
                    <Text style={{ margin: 5 }}>
                        {item.address}
                    </Text>
                </TouchableOpacity> */}


                // <View style={styles.searchBar}>
                //     <View style={{ height: 50, borderWidth: 1, borderColor: 'black', borderRadius: 15, margin: 15, flexDirection: 'row' }}>
                //         <View style={{ flex: 1 }}>
                //         </View>
                //         <View style={{ flex: 4 }}></View>
                //         <View style={{ flex: 1 }}></View>
                //     </View>
                // </View>
                // <View style={styles.btnAddress}>
                //     <TouchableOpacity onPress={() => this.addAdreess()}>
                //         <View style={{ height: 40, borderRadius: 15, marginRight: 70, marginLeft: 70, backgroundColor: '#CFB368', justifyContent: 'center', alignContent: 'center' }}>
                //             <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', color: 'white', fontSize: 20 }}> +  Tambah Alamat </Text>
                //         </View>
                //     </TouchableOpacity>

                // </View>
                // <View style={styles.listAddress}>
                //     <FlatList
                //         data={this.state.data}
                //         renderItem={this.renderItem}
                //         keyExtractor={item => item.id}
                //     />
                // </View>




            //     <View style={styles.body}>
            //     {/* <ScrollView> */}
            //     <View style={styles.btn_addreess}>
            //         <Button title="Tambah Alamat" onPress={() => this.addAdreess()}></Button>
            //     </View>

            //     <FlatList
            //         data={this.state.data}
            //         renderItem={this.renderItem}
            //         keyExtractor={item => item.id}
            //     />
            // </View>