import React from 'react';
import { View, Text, StyleSheet, FlatList, TextInput, Alert, Linking, ActivityIndicator } 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';
import RNPickerSelect from 'react-native-picker-select';
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps';
import { Icon } from 'react-native-elements'

class Outlets 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,
            data_outlet: [],
            outlet_selected: '',
            data_name: '',
            indicator: true
        }
    }

    componentDidMount() {

        this._unsubscribe = this.props.navigation.addListener('focus', () => {
            this.setState({
              indicator: true,
            })
            this._getOutletClosest()
            this.OrderedList()
            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()
    }

    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;

                // console.log("INI YAA: " + JSON.stringify(dataOutlets));
            }

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

    OrderedList() {
        Axios.get("https://excelsocrm.ravintoladev.com/crm/v2/outlet/get_city_list").then(res => {

            let cities = res.data.city
            let data_city = []

            for (const city in cities) {
                if (cities.hasOwnProperty(city)) {
                    const label = cities[city];
                    const value = city;
                    data_city.push({ label: label, value: label })
                }
            }

            // console.log("ISI DATANYA : " + JSON.stringify(data_city))

            this.setState({
                data_outlet: data_city
            })

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

    _getOutletClosest() {
        let params = {
            session_id: this.props.session_id,
            lat: this.props.lat,
            long: this.props.long
        }
        // console.log(params);
        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/outlet/get_closest', params).then(res => {

            let outletName = res.data.data.outlet_name
            this.setState({
                indicator: false,
                data_name: outletName
            })

            // console.log("INI ADALAH RESPON :  + " + JSON.stringify(res))

            // console.log("INI DATANYA NAME : " + outletName)
        }).catch(error => {
            const { navigation } = this.props
            let response = error.response.data
            session(response, navigation)
            Alert.alert(response.msg);
        })
    }

    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(value) {
        let filteredOutlets = this.state.data_before_search.filter(item => {
            return item.city.indexOf(value) > -1;

        });
        if (value === '') {
            this.setState({
                dataOutlets: this.state.data_before_search,
                search: ''
            })
        } else if (value == null) {
            this.setState({
                dataOutlets: this.state.data_before_search,
                search: ''
            })
        }
        else {
            this.setState({
                dataOutlets: filteredOutlets,
                search: value
            });
        }

    }

    RenderItem = ({ item }) => {
        return (

            <View style={{ flexDirection: 'row', flex: 1, marginRight: 20, marginLeft: 20, marginBottom: 20 }}>
                <View style={styles.content_list}>
                    <View style={styles.list_addrees}>
                        <Text style={{ fontFamily: 'Gotham-Black', color: '#ccb46c', fontSize: 18 }}>{item.name}</Text>
                        <Text style={{ flexWrap: 'wrap', fontFamily: 'Gotham-Light', color: '#b1b1b2' }}>{item.full_address}</Text>
                        <Text style={{ fontFamily: 'Gotham-Light', color: '#aeaead' }}>
                            {item.distance} KM
                    </Text>
                    </View>
                    <View style={{ flex: 2, flexDirection: 'row' }}>
                        <View style={{ margin: 5 }}>
                            <TouchableOpacity onPress={() => { Linking.openURL('tel:' + item.phone) }}>
                                <Icon
                                    name='ios-call'
                                    type='ionicon'
                                    color='grey'
                                    size={38}
                                />
                            </TouchableOpacity>
                        </View>
                        <View style={{ margin: 5 }}>
                            <TouchableOpacity onPress={() => Linking.openURL('https://www.google.com/maps/dir/?api=1&destination=' + item.lat + ' ' + item.long)}>
                                <Icon
                                    name='ios-navigate'
                                    type='ionicon'
                                    color='grey'
                                    size={38}
                                />
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>

            </View>
        );
    }
    render() {

        return (
            <View style={styles.container}>
                {/* <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                /> */}
                <View style={{ flex: 1 }}>
                    <MapView style={{ flex: 1, marginRight: 10, marginLeft: 10 }}
                        region={{
                            latitude: this.state.my_lat,
                            longitude: this.state.my_long,
                            latitudeDelta: 0.1,
                            longitudeDelta: 0.1,

                        }}
                        zoomEnabled={true}
                        loadingEnabled={true}
                        provider={PROVIDER_GOOGLE}
                    >
                        <MapView.Marker
                            coordinate={{
                                latitude: this.state.my_lat,
                                longitude: this.state.my_long
                            }}
                            title={"Lokasi Kamu "}
                            description={this.state.street}
                        />

                    </MapView>
                </View>
                <View style={{ height: 50, flexDirection: 'row' }}>
                    <View style={{ flex: 1 }}></View>
                    <View style={{ flex: 1 }}>
                        <RNPickerSelect
                            placeholder={{ label: 'All city' }}
                            onValueChange={(label) => this.filterData(label)}
                            items={this.state.data_outlet}
                        />
                    </View>
                </View>
                <View style={styles.body}>
                    {this.state.dataOutlets.length > 0 ? (
                        <FlatList
                            data={_.orderBy(this.state.dataOutlets, ['distance'], ['asc'])}
                            renderItem={this.RenderItem}
                            keyExtractor={item => item.id}
                            windowSize={5}
                            initialNumToRender={18}
                            maxToRenderPerBatch={2}
                            onEndReachedThreshold={0.5}
                        />
                    ) : (
                        <Text style={{ flexWrap: 'wrap', fontFamily: 'Gotham-Light', color: '#b1b1b2', textAlign:'center' }}> Tidak Ada Outlets di area anda !</Text>
                        )}

                </View>
            </View>
        )
    }
}


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

    },
    header: {

        flex: 0.5,
    },

    body: {
        flex: 1,
    },
    list_addrees: {
        flex: 6,
    },

    searchbar: {
        flex: 1,
        justifyContent: 'center',
        margin: 10,
    },
    content_list: {
        flex: 1,
        flexDirection: 'row',
    }
})

const mapStateToProps = (state) => {
    return {

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

export default connect(mapStateToProps)(Outlets);

{/* <View style={{flex:1,backgroundColor:'red'}}>
           
                  </View>

                    <View style={{ flexDirection: 'row', flex: 1 }}>
                        <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> */}