import React from 'react';
import { View, Text, StyleSheet, Button, FlatList, Alert } from 'react-native';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import { connect } from 'react-redux';
import Axios from 'axios';
import ActionType from '../redux/globalActionType';
import ravLog from '../helper/debug';

class DeliveryAddrees extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            // 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;
            let address = []
            for (let i = 0; i < dataAlamat.length; i++) {
                const element = dataAlamat[i];
                address.push(element)

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

    getRate() {

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

        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 : ' +  res.data.data.amount)


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


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

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


    onSave(address, id) {

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

        this.props.setAddress(setDataAddress);

        this.getRate()

        this.props.setTypePickup(false)

        // console.log(this.props)

        if (this.props.route.params.from == 'shoppingCart') {
            this.props.navigation.navigate('Shopping Cart')
        } else {
            this.props.navigation.navigate("Menu Select")
        }



        // 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={{ margin: 5, }}>
                        <Text style={{ fontWeight: 'bold', fontSize: 20 }}>{item.name}</Text>
                    </View>
                    <Text style={{ margin: 5 }}>
                        {item.address}
                    </Text>
                    <Text style={{ margin: 5 }}>
                        Patokan : {item.description}
                    </Text>
                </TouchableOpacity>
            </View>
        );
    }
    render() {


        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <Text style={{ textAlign: 'center', margin: 20, fontSize: 25, alignSelf: 'center' }}>Delivery Address</Text>
                </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>
            </View>
        )
    }
}

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

        flex: 0.5,
    },

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

    btn_addreess: {
        margin: 20,
    },

    list_addrees: {
        flex: 1,
        margin: 20,

        borderWidth: 1,
    }
})

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)

