import React from 'react';
import { View, Text, StyleSheet, FlatList, TextInput, Alert } from 'react-native';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import Spinner from 'react-native-loading-spinner-overlay';
import { CheckBox } from 'react-native-elements';
import ActionType from '../redux/globalActionType';
import Axios from 'axios';
import { MaterialCommunityIcons, Ionicons } from '@expo/vector-icons';
import _ from 'lodash';
import * as Location from 'expo-location';
import { connect } from 'react-redux';
import * as Permissions from 'expo-permissions';
import * as Device from 'expo-device';

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

    componentDidMount() {

        this._getPermissions()
        
    }

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

            Alert.alert('Silahkan anda coba di real Device')
        } 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) {
        
        let OutletChange = {
            outlet_id: id ,
            name_outlet:name,   
        }

        this.props.setChangeOutletProps(OutletChange);
        this.props.navigation.navigate("Menu Select")
    }

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

        Axios.post("https://excelsocrm.ravintoladev.com/crm/v2/outlet/get_list", params).then(res => {
            let dataOutlets = res.data.outlets;
            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({
                spinner: false,
            })

        }).catch(error => {
            let response = error.response.data;
            Alert.alert(response.msg);
                this.setState({
                    spinner: 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 style={{ flexDirection: 'row', flex: 1 }}>
                <View>
                    <MaterialCommunityIcons name="map-marker" size={32} color="brown" />
                </View>
                <View style={styles.list_addrees}>
                    <View style={{ margin: 5 }}>
                        <Text style={{ fontWeight: 'bold', fontSize: 20 }}>{item.name}</Text>
                        <Text style={{ fontWeight: 'bold', fontSize: 15, color: '#ccb46c' }}>OPEN - </Text>
                    </View>
                    <Text style={{ margin: 5, color: '#b1b1b2' }}>
                        {item.full_address}
                    </Text>
                    <Text style={{ margin: 5, color: '#aeaead' }}>
                        {item.distance} KM
               </Text>
                </View>
                <View>
                    <TouchableOpacity onPress={() => this.getOutletDetail(item.id, item.name)}>
                        <CheckBox
                            center
                            checkedIcon='dot-circle-o'
                            uncheckedIcon='circle-o'
                            checked={this.state.checked}
                        />
                    </TouchableOpacity>

                </View>
            </View>
        );
    }
    render() {

        return (
            <View style={styles.container}>
                 <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 }}>
                            <MaterialCommunityIcons name="map-marker" size={32} color="brown" />
                        </View>
                        <View style={{ flex: 6 }}>
                            <TextInput style={{ height: 45 }} placeholder="Cari lokasi Pickup Store"
                                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="brown" />
                        </View>
                    </View>

                </View>
                <View style={styles.body}>
                    <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: 1,
        justifyContent: 'center',
        margin: 10,
    }
})

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

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

            }
        }),
    }
}

const mapStateToProps = (state) => {
    return {

        session_id: state.session_id,
        outlet_id: state.outlet_id,
        name_outlet: state.name_outlet,
    }
}

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

