import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import Axios from 'axios';
import * as Device from 'expo-device';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import i18n from 'i18n-js';
import _ from 'lodash';
import React from 'react';
import { ActivityIndicator, Alert, FlatList, 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';

class PickupName extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            city: [],
            city_selected: '',
            dataOutlets: [],
            my_lat: 0,
            my_long: 0,
            distance: [],
            search: '',
            data: [], // data yg sedang aktif
            data_before_search: [],
            spinner: false,
            indicator: true,
            caretHidden:true
        }
    }

    componentDidMount() {

        this._getPermissions()
        // console.log("INI BASE : " + this.props.BASE_URL)

    }


    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 => {

            if (this.state.state_add_remove_voucher == true) {
                this.setState({
                    state_add_remove_voucher: false
                })
                this.props.removeVoucher()
            } else{
                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.toString())
            }
        })
    }

    _getPermissions = async () => {
        let { status } = await Permissions.askAsync(Permissions.LOCATION);
        if (status !== 'granted') {
            Alert.alert(i18n.t('accessNotPermitted'))
        } else if (Platform.OS === 'android' && !Device.isDevice) {

            Alert.alert(i18n.t('tryItRealDevice'))
        } else {
            this._getCurrentPosisition()
        }
    }
    _getCurrentPosisition = async () => {
        this.setState({
            spinner: true,
        })
        let location = await Location.getCurrentPositionAsync({
            accuracy: Location.Accuracy.Highest
        })

        let latitude = location.coords.latitude;
        let longitude = location.coords.longitude;

        this.setState({
            my_lat: latitude,
            my_long: longitude
        })
        this.getOutlet()
    }

    getOutletDetail(id, name, address) {

        if (this.props.value_voucher !== "") {
            this.handleVoucherSelect()
            
        }else{
            let OutletChange = {
                outlet_id: id,
                name_outlet: name,
                outlet_detailadress: address
            }
    
            this.props.setChangeOutletProps(OutletChange);
            this.props.setTypePickup(true);
    
            if (this.props.route.params.from == 'shoppingCart') {
                this.props.navigation.navigate('Shopping Cart', { outlet_change: true, outlet_id: id })
            } else {
    
                this.props.navigation.navigate('Home', {
                    screen: 'MENU',
                    params: { user: 'jane' },
                })
            }
        }
        
    }

    getOutlet() {
        this.setState({
            spinner: true,
        })
        let params = {
            session_id: this.props.session_id
        }

        Axios.post(this.props.BASE_URL+"crm/v2/outlet/get_list", params).then(res => {
            let dataOutlets = res.data.outlets;
            // console.log("INI ADALAH DATA OUTLETS : " + JSON.stringify(dataOutlets))
            for (let i = 0; i < dataOutlets.length; i++) {
                dataOutlets[i]['distance'] = this.distance(dataOutlets[i]['lat'], dataOutlets[i]['long']);
                let address = dataOutlets[i]['address'];
                if (dataOutlets[i]['city'] !== '') {
                    if (address !== '') {
                        address = address + ', ' + dataOutlets[i]['city'];
                    } else {
                        address = dataOutlets[i]['city'];
                    }
                }
                if (dataOutlets[i]['province']) {
                    if (address !== '') {
                        address = address + ', ' + dataOutlets[i]['province'];
                    } else {
                        address = dataOutlets[i]['province'];
                    }
                }
                if (dataOutlets[i]['postal_code']) {
                    if (address !== '') {
                        address = address + ' ' + dataOutlets[i]['postal_code'];
                    } else {
                        address = dataOutlets[i]['postal_code'];
                    }
                }
                dataOutlets[i]['full_address'] = address;
            }
            this.setState({
                dataOutlets: dataOutlets,
                data_before_search: dataOutlets,

            })
            this.setState({
                indicator: false,
            })

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

    toRad(value) {
        return value * Math.PI / 180;
    }

    distance(locationLat, locationLong) {

        let R = 6371;
        let dLat = this.toRad(locationLat - this.state.my_lat);  // Javascript functions in radians
        let dLon = this.toRad(locationLong - this.state.my_long);
        let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.toRad(this.state.my_lat)) * Math.cos(this.toRad(locationLat)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        let d = R * c;
        return Math.round(d * 10) / 10;

    }

    clear = () => {
        this.state.search.clear();
    };

    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({
                dataOutlets: this.state.data_before_search,
                search: ''
            })
        } else {
            this.setState({
                dataOutlets: newData,
                search: text
            });
        }
    }

    select(item) {
     
            let OutletChange = {
                outlet_id: item.id,
                name_outlet: item.name,
            }
            this.props.setChangeOutletProps(OutletChange)
      

        this.props.navigation.navigate('Home', { screen: 'MENU' });
    }

    RenderItem = ({ item }) => {
        return (
            <View>
                {
                    item.pickup == true ? (
                        item.can_accept_order == true ? (
                            <View>
                                <TouchableOpacity onPress={() => this.getOutletDetail(item.id, item.name, item.full_address)}>
                                    <View style={{ flexDirection: 'row', flex: 1 }}>
                                        <View style={{ top: 10 }}>
                                            <MaterialCommunityIcons name="map-marker" size={32} color="#ccb46c" />
                                        </View>
                                        <View style={styles.list_addrees}>
                                            <View style={{ margin: 5 }}>
                                                <Text style={{ fontFamily: 'Gotham-Black', color: 'grey', fontSize: 20 }}>{item.name}</Text>
                                                <View style={{ flexDirection: 'row' }}>
                                                    {item.can_accept_order == true ? (<Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c", top: 5 }}>{i18n.t('open')}    </Text>)
                                                      : (<Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c" }}>{i18n.t('closed')}  </Text>)}
                                                </View>
                                            </View>
                                            <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368' }}>{i18n.t('openinghours')}  : {item.open_time} - {item.close_time}</Text>
                                            <Text style={{ margin: 5, color: '#b1b1b2', fontFamily: 'Gotham-Light' }}>
                                                {item.full_address}
                                            </Text>
                                        </View>
                                        <View>
                                            <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' }}>{item.distance} KM</Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        ) : (<View>
                            <View>
                                <TouchableOpacity onPress={() => Alert.alert('', 'Mohon Maaf Outlet Tutup !')}>
                                    <View style={{ flexDirection: 'row', flex: 1 }}>
                                        <View style={{ top: 10 }}>
                                            <MaterialCommunityIcons name="map-marker" size={32} color="#ccb46c" />
                                        </View>
                                        <View style={styles.list_addrees}>
                                            <View style={{ margin: 5 }}>
                                                <Text style={{ fontFamily: 'Gotham-Black', color: 'grey', fontSize: 20 }}>{item.name}</Text>
                                                <View style={{ flexDirection: 'row' }}>
                                                    {item.can_accept_order == true ? (<Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c", top: 5 }}>{i18n.t('open')}  </Text>)
                                                        : (<Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c" }}>{i18n.t('closed')}  </Text>)}
                                                </View>
                                            </View>
                                            <Text style={{ fontFamily: 'Gotham-Light', color: '#CFB368' }}> {i18n.t('openinghours')} : {item.open_time} - {item.close_time}</Text>
                                            <Text style={{ margin: 5, color: '#b1b1b2', fontFamily: 'Gotham-Light' }}>
                                                {item.full_address}
                                            </Text>
                                        </View>
                                        <View>
                                            <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' }}>{item.distance} KM</Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            </View>

                        </View>)
                    ) : (
                            null
                        )
                }
            </View>


        );
    }
    render() {

        return (
            <View style={styles.container}>
                <MyStatusBar />
                {/* <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                /> */}
                <View style={styles.searchbar}>
                    <View style={{ height: 45, borderRadius: 10, borderColor: '#ccb46c', borderWidth: 1, flexDirection: 'row' }}>
                        <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('searchpickups')}
                                onChangeText={text => this.filterData(text)}
                                onClear={text => this.filterData('')}
                                value={this.state.search} 
                                caretHidden={this.state.caretHidden}
                                onFocus={() => this.setState({caretHidden: false})}></TextInput>
                        </View>
                        <View style={{ flex: 1, margin: 5 }}>
                            <Ionicons name="ios-search" size={32} color="#ccb46c" />
                        </View>
                    </View>
                </View>
                <View style={styles.body}>
                    {this.state.indicator == true ? (
                        <ActivityIndicator size="large" color="#c9af6d" />
                    ) : (
                            <FlatList
                                data={_.orderBy(this.state.dataOutlets, ['distance'], ['asc'])}
                                renderItem={this.RenderItem}
                                keyExtractor={item => item.id}
                                windowSize={5}
                                initialNumToRender={18}
                                maxToRenderPerBatch={2}
                                onEndReachedThreshold={0.5}
                            />
                        )}

                </View>
            </View>
        )
    }
}


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

        flex: 0.5,
    },

    body: {
        flex: 5,
        margin: 20,
    },
    list_addrees: {
        flex: 2,
        margin: 5,
    },

    searchbar: {
        flex: 0.5,
        justifyContent: 'center',
        top: 10,
        marginRight: 20,
        marginLeft: 20,
    }
})

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

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

            }
        }),
        setTypePickup: (type) => dispacth({
            type: ActionType.SET_TYPE,
            data: {
                type_pickup: type
            }
        }),
        setRecalculate: (recalculateProps) => dispacth({
            type: ActionType.SET_RECALCULATE,
            data: {

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

            }
        }),
        removeVoucher: () => dispacth({
            type: ActionType.REMOVE_VOUCHER
        }),
    }
}

const mapStateToProps = (state) => {
    return {

        session_id: state.session_id,
        outlet_id: state.outlet_id,
        name_outlet: state.name_outlet,
        outlet_detailadress: state.outlet_detailadress,
        language: state.language,
        value_voucher: state.value_voucher,
        voucher: state.voucher,
        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,
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(PickupName);

