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 React from 'react';
import { ActivityIndicator, Alert, Platform, StyleSheet, Text, TextInput, View, KeyboardAvoidingView } from 'react-native';
import { ScrollView, TouchableOpacity } from 'react-native-gesture-handler';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
import { connect } from 'react-redux';
import session from '../function/session';

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

    componentDidMount() {

        this._getPermissions();
    }

    //Permission (melakukan izin)
    _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._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)
        //ini benerin bug ketika jalan kosong
        let street = detail[0].street
        let city = detail[0].city
        let region = detail[0].region
        let postalCode = detail[0].postalCode
        let latitude = location.coords.latitude;
        let longitude = location.coords.longitude;
        this.setState({ location, latitude: latitude, longitude: longitude })

        if (street == null) {
            let str_city = city.replace('null', '')
            let str_region = region.replace('null', '')
            let str_postalCode = postalCode.replace('null', '')

            this.setState({
                street: '',
                city: str_city,
                region: str_region,
                postalCode: str_postalCode,
                indicator: false,

            })

        } else if (city == null) {
            let str_street = street.replace('null', '')
            let str_region = region.replace('null', '')
            let str_postalCode = postalCode.replace('null', '')

            this.setState({
                street: str_street,
                city: '',
                region: str_region,
                postalCode: str_postalCode,
                indicator: false,
            })

        } else if (region == null) {
            let str_street = street.replace('null', '')
            let str_city = city.replace('null', '')
            let str_postalCode = postalCode.replace('null', '')

            this.setState({
                street: str_street,
                city: str_city,
                region: '',
                postalCode: str_postalCode,
                indicator: false,
            })

        } else if (postalCode == null) {

            let str_street = street.replace('null', '')
            let str_city = city.replace('null', '')
            let str_region = region.replace('null', '')

            this.setState({
                street: str_street,
                city: str_city,
                region: str_region,
                postalCode: '',
                indicator: false,
            })
        } else {
            let str_street = street.replace('null', '')
            let str_city = city.replace('null', '')
            let str_region = region.replace('null', '')
            let str_postalCode = postalCode.replace('null', '')

            this.setState({

                street: str_street,
                city: str_city,
                region: str_region,
                postalCode: str_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(i18n.t('alertAddressNotFound'));
        } 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(this.props.BASE_URL + 'crm/v2/member/set_address', params).then(res => {
            Alert.alert(
                i18n.t('alertSuccessAddAddressTitle'),
                i18n.t('alertSuccessAddAddressContent')

            )
            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 (
            <KeyboardAvoidingView
                behavior={Platform.OS == 'ios' ? "padding" : "height"}
                style={{ flex: 1 }}>


                <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={i18n.t('findAddress')}
                                        caretHidden={this.state.caretHidden}
                                        onFocus={() => this.setState({ caretHidden: false })}
                                        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}
                                    provider={PROVIDER_GOOGLE}
                                    style={styles.cont_google_map}>
                                    <MapView.Marker
                                        coordinate={{
                                            latitude: this.state.latitude,
                                            longitude: this.state.longitude
                                        }}
                                        title={i18n.t('yourLocation')}
                                        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 }}>{i18n.t('label')}</Text>
                                    <TextInput style={{ color: 'grey', fontFamily: 'Gotham-Black', height: 40, borderWidth: 1, padding: 5, flex: 1, margin: 10, borderRadius: 10, borderColor: 'grey', textAlign: 'center' }}
                                        onChangeText={(name) => this.setState({ name })}
                                        caretHidden={this.state.caretHidden}
                                        onFocus={() => this.setState({ caretHidden: false })} />
                                </View>

                                <View style={styles.field_detail_addrees}>
                                    <Text style={{ fontFamily: 'Gotham-Black', color: "#ccb46c", textAlign: 'center', fontSize: 18 }}>{i18n.t('detail')}</Text>
                                    <TextInput
                                        style={{ color: 'grey', fontFamily: 'Gotham-Black', textAlign: 'center', height: 70, borderWidth: 1, padding: 5, flex: 1, margin: 10, borderRadius: 10, borderColor: 'grey' }}
                                        onChangeText={(description) => this.setState({ description })}
                                        numberOfLines={10}
                                        multiline={true}
                                        caretHidden={this.state.caretHidden}
                                        onFocus={() => this.setState({ caretHidden: false })} />
                                </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' }}>{i18n.t('addaddress')}</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                                <View style={{ height: 20 }}></View>
                            </View>
                        </View>
                    </ScrollView>
                </View>
            </KeyboardAvoidingView>
        )
    }
}

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: {
        top: 40,
    },

    button: {
        height: 40,
        margin: 10,

    },
})

const mapStateToProps = (state) => {
    return {

        session_id: state.session_id,
        language: state.language,
        BASE_URL: state.BASE_URL,


    }
}


export default connect(mapStateToProps)(AddreesDetail)