import React from 'react';
import { View, Text, TextInput, StyleSheet, Button, Platform, Dimensions, Alert, Image } from 'react-native';
import * as Device from 'expo-device';
import * as Permissions from 'expo-permissions';
import * as Location from 'expo-location';
import MapView, { Marker } from 'react-native-maps';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import { connect } from 'react-redux';
import Axios from 'axios';
import Spinner from 'react-native-loading-spinner-overlay';

 class AddreesDetail extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            latitude: 0,
            longitude: 0,
            location: null,
            error_message: null,
            name:'',
            address_id:'',
            description:'',
            lat:'',
            long:'',
            street: '',
            city: '',
            region: '',
            name: '',
            postalCode: '',
            address: '',
            address_d:'',
            spinner: false,
        }
    }

    componentDidMount() {

        this._getPermissions();
    }

    //Permission (melakukan izin)
    _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._getLocationAsync()
        }
    }

    //Current location (lokasi saat ini)
    _getLocationAsync = async () => {
        this.setState({
            spinner: true,
        })
        let location = await Location.getCurrentPositionAsync({
            accuracy: Location.Accuracy.Highest
        })

        let detail = await Location.reverseGeocodeAsync(location.coords)
        console.log(" INI DETAIL "+ JSON.stringify(detail) )
        let latitude = location.coords.latitude;
        let longitude = location.coords.longitude;
        this.setState({ location, latitude: latitude, longitude: longitude })

        this.setState({

            street: detail[0].street,
            city: detail[0].city,
            // name: detail[0].name,
            region: detail[0].region,
            postalCode: detail[0].postalCode,
            

        })

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

    //searchlocation (mencari lokasi)
    _searchLocation = async () => {

        let search_location = await Location.geocodeAsync(this.state.address, Location.Accuracy.Balanced)
        if (search_location.length === 0) {
            Alert.alert('Alamat tidak di temukan!');
        } else {
            let detail = await Location.reverseGeocodeAsync(search_location[0])
          
            this.setState({
                latitude: search_location[0].latitude,
                longitude: search_location[0].longitude,
                street: detail[0].street,
                city: detail[0].city,
                // name: detail[0].name,
                region: detail[0].region,
                postalCode: detail[0].postalCode,
            })
        }

        console.log('LATITUDE' + '' + this.state.latitude + '' + 'LONGITUDE' + this.state.longitude)
    }

    saveAddress() {

        this.setState({
            spinner: true,
        })
        const navigation = this.props.navigation
       
        let params = {
            session_id: this.props.session_id,
            address_id: '',
            address: this.state.street + ' ' + this.state.city + ' ' + this.state.region + ' ' + this.state.postalCode ,
            name: this.state.name,
            description: this.state.description ,
            lat: this.state.latitude,
            long: this.state.longitude
        }
        console.log(params)

        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/set_address', params).then(res => {
            Alert.alert(
                'Berhasil',
                'Berhasil menambahkan Alamat !'
                
            )
            this.setState({
                spinner: false,
            })
            this.props.navigation.goBack()
            this.props.route.params.onChangeAddress({ example: 'wakwaw' })

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

    render() {
        return (
            <View style={styles.container}>
                 <Spinner
                    visible={this.state.spinner}
                    textContent={'Loading...'}
                    textStyle={styles.spinnerTextStyle}
                />
                <ScrollView>
                    <View style={styles.header}>
                        <Text style={{ textAlign: 'center', marginTop: 10, fontSize: 25 }}>Tambah Alamat</Text>
                    </View>
                    <View style={styles.content}>
                        <View style={styles.field_search}>
                            <View style={{ width: 55, justifyContent: 'center' }}>
                                <Text>Cari</Text>
                            </View>
                            <View style={{ flex: 1 }}>
                                <TextInput style={{ height: 40, borderWidth: 1, padding: 5, margin: 10 }} onChangeText={(address) => this.setState({ address })} />
                            </View>
                            <View style={{ alignSelf: 'center' }}>
                                <Button title="cari" onPress={() => this._searchLocation()}></Button>
                            </View>
                        </View>
                        <View style={styles.cont_google_map}>
                            <MapView
                                region={{

                                    latitude: this.state.latitude,
                                    longitude: this.state.longitude,
                                    latitudeDelta: 0.1,
                                    longitudeDelta: 0.1,

                                }}
                                zoomEnabled={true}
                                showsMyLocationButton={true}
                                loadingEnabled={true}
                                showsUserLocation={true}
                                showsScale={true}
                                style={styles.cont_google_map}
                            />
                            <View style={{ position: 'absolute', top: '50%', alignSelf: 'flex-end' }}>
                                <View style={{ margin: 15 }}>
                                    <TouchableOpacity style={{ height: 30, width: 30, backgroundColor: '#e6e6e6' }} onPress={() => this._getLocationAsync()}>
                                        <Image source={require('../assets/icon/gps.png')} style={{ height: 30, width: 30 }} />
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                        <View style={styles.name_addrees_input}>
                            <View style={styles.field_name_addrees}>
                                <View style={{ width: 55, justifyContent: 'center' }}>
                                    <Text>Nama</Text>
                                </View>
                                <TextInput style={{ height: 40, borderWidth: 1, padding: 5, flex: 1, margin: 10 }} onChangeText={(name) => this.setState({ name })} />
                            </View>

                            <View style={styles.field_detail_addrees}>
                                <View style={{ width: 55, justifyContent: 'center' }}>
                                    <Text>Detail</Text>
                                </View>
                                <TextInput style={{ height: 80, borderWidth: 1, padding: 5, flex: 1, margin: 10 }} onChangeText={(description) => this.setState({ description })} />
                            </View>
                            <View style={styles.field_name_addrees}>
                                <View style={{ width: 55, justifyContent: 'center' }}>
                                    <Text>Alamat</Text>
                                </View>
                                <View style={{ flex: 1, height: 80, borderWidth: 1, padding: 5, margin: 10 }}>
                                    <View style={{ padding: 5 }}>
                                    <Text>{this.state.street}</Text>
                                    <Text>{this.state.city}</Text>
                                    <Text>{this.state.region}</Text>
                                    <Text>{this.state.postalCode}</Text>
                                    </View>
                                </View>
                            </View>
                            <View style={{ margin: 50, justifyContent: 'center' }}>
                                <Button title="Simpan" onPress={() => this.saveAddress()} />
                            </View>
                        </View>
                    </View>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: '#ffff'
    },

    header: {
        flex: 0.5,
        margin: 5,
    },

    content: {
        flex: 3,
        margin: 5,
    },

    field_search: {
        flexDirection: 'row'
    },

    cont_google_map: {
        flex: 1,
        borderWidth: 1,
        margin: 5,
        height: 250,
    },

    name_addrees_input: {
        flex: 1,
        margin: 5,
    },

    field_name_addrees: {
        flexDirection: 'row'
    },

    field_detail_addrees: {
        flexDirection: 'row'
    },

    button: {
        height: 40,
        margin: 10,

    },
})

const mapStateToProps = (state) => {
    return {
  
      session_id: state.session_id,

    }
  }
  
  export default connect(mapStateToProps)(AddreesDetail)