import React from 'react';
import { View, Text, TextInput, StyleSheet, Button, Platform, Dimensions, Alert, Image ,ActivityIndicator } 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';
import { MaterialCommunityIcons, Ionicons } from '@expo/vector-icons';
import ActionType from '../redux/globalActionType';

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,
            indicator: true,
        }
    }

    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,
            indicator: 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;
            const { navigation } = this.props
            session(response, navigation)
            Alert.alert(
                '',
                response.msg
            )
            this.setState({
                spinner: false,
            })
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <ScrollView>
                    <View style={styles.content}>
                        <View style={{ height: 45, borderRadius: 10, borderColor: '#ccb46c', borderWidth: 1, flexDirection: 'row', marginTop: 15, marginLeft: 10, marginRight: 10 }}>
                            <View style={{ flex: 1, top: 5 }}>
                                <MaterialCommunityIcons name="map-marker" size={32} color="#ccb46c" />
                            </View>
                            <View style={{ flex: 6 }}>
                                <TextInput style={{ height: 45 }} placeholder="Cari Alamat"
                                    onChangeText={(address) => this.setState({ address })}>
                                </TextInput>
                            </View>
                            <View style={{ flex: 1, margin: 5 }}>
                                <TouchableOpacity onPress={() => this._searchLocation()}>
                                    <Ionicons name="ios-search" size={32} color="#ccb46c" />
                                </TouchableOpacity>
                            </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}>
                                <MapView.Marker
                                    coordinate={{
                                        latitude: this.state.latitude,
                                        longitude: this.state.longitude
                                    }}
                                    title={"Lokasi Kamu "}
                                    description={this.state.street}
                                />
                            </MapView>
                            <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={{ flexDirection: 'row', top: 10, justifyContent: 'center' }}>
                                <View style={{ flex: 1, justifyContent: 'center', flexDirection: 'row' }}>
                                    <MaterialCommunityIcons name="map-marker" size={32} color="#ccb46c" />
                                </View>
                                {this.state.indicator == true ? (
                                    <ActivityIndicator size="large" color="#c9af6d" />
                                ) : (
                                        <View style={{ flex: 3, justifyContent: 'center' }}>
                                            <Text style={{ fontFamily: 'Gotham-Light', textAlign: 'center' }}>{this.state.street}</Text>
                                            <Text style={{ fontFamily: 'Gotham-Light', textAlign: 'center' }}>{this.state.city} </Text>
                                            <Text style={{ fontFamily: 'Gotham-Light', textAlign: 'center' }}>{this.state.region}</Text>
                                            <Text style={{ fontFamily: 'Gotham-Light', textAlign: 'center' }}>{this.state.postalCode}</Text>
                                        </View>
                                    )}


                                <View style={{ flex: 1 }}>
                                </View>
                            </View>
                            <View style={styles.field_name_addrees}>
                                <Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c", textAlign: 'center', fontSize: 18 }}>Label</Text>
                                <TextInput style={{ height: 40, borderWidth: 1, padding: 5, flex: 1, margin: 10, borderRadius: 10, borderColor: 'grey' }} onChangeText={(name) => this.setState({ name })} />
                            </View>

                            <View style={styles.field_detail_addrees}>

                                <Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c",textAlign:'center', fontSize: 18 }}>Detail</Text>
                                <TextInput 
                                    style={{ height: 150, borderWidth: 1, padding: 5, flex: 1, margin: 10, borderRadius: 10, borderColor: 'grey' }}
                                    onChangeText={(description) => this.setState({ description })}
                                    numberOfLines={10}
                                    multiline={true} />
                            </View>
                            <View style={{ margin: 50, justifyContent: 'center' }}>
                                <TouchableOpacity onPress={() => this.saveAddress()}>
                                    <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', justifyContent: 'center' }}>
                                        <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center' }}> Tambah Alamat</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({

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

    },

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

    content: {
        flex: 3,
        marginRight: 10,
        marginLeft: 10,
    },

    field_search: {
        flexDirection: 'column'
    },

    cont_google_map: {
        flex: 1,
        top: 5,
        marginRight: 10,
        marginLeft: 10,
        height: 250,
    },

    name_addrees_input: {
        flex: 1,
        marginLeft: 10,
        marginRight: 10,
        top: 20
    },

    field_name_addrees: {
        flexDirection: 'column',
        top: 40,
        justifyContent: 'center'
    },

    field_detail_addrees: {
        flexDirection: 'column',
        top: 40,
    },

    button: {
        height: 40,
        margin: 10,

    },
})

const mapStateToProps = (state) => {
    return {

        session_id: state.session_id,

    }
}


export default connect(mapStateToProps)(AddreesDetail)

//   <TextInput style={{ height: 40, borderWidth: 1, padding: 5, margin: 10,borderRadius:5 }} onChangeText={(address) => this.setState({ address })} />