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 { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import { connect } from 'react-redux';
import session from '../function/session';

class EditAddressDetail 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() {
        // console.log(this.props.route.params)
        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
        // })
        // console.log(location)
        let loc = {
            latitude: parseFloat(this.props.route.params.lat),
            longitude: parseFloat(this.props.route.params.long),
        }
        // console.log(loc)
        let detail = await Location.reverseGeocodeAsync(loc)
        //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 = parseFloat(this.props.route.params.lat);
        let longitude = parseFloat(this.props.route.params.long);
        this.setState({ 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,
            })
        }

        this.setState({
            name:this.props.route.params.name,
            description:this.props.route.params.address
        })





    }

    //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 {
            // console.log('bugging : ' + JSON.stringify(search_location))
            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)
    }

    validation() {
        if (this.state.name == '') {
            Alert.alert(i18n.t('alertLabelAddress'))
        } else if (this.state.description == '') {
            Alert.alert(i18n.t('alertDetailAddress'))
        } else {
            this.saveAddress()
        }
    }

    onChangeLocation = async (e) => {
        // console.log(e.nativeEvent.coordinate)
        this.setState({
            latitude: e.nativeEvent.coordinate.latitude,
            longitude: e.nativeEvent.coordinate.longitude,
        })
        let detail = await Location.reverseGeocodeAsync(e.nativeEvent.coordinate)
        // console.log('ini detail : ', detail)
        this.setState({
            street: detail[0].street,
            city: detail[0].city,
            // name: detail[0].name,
            region: detail[0].region,
            postalCode: detail[0].postalCode,
        })
    }

    onSubmit = async (location) => {
        let loc = {
            latitude: location.lat,
            longitude: location.lng
        }
        let detail = await Location.reverseGeocodeAsync(loc)
        // console.log(detail)
        this.setState({
            latitude: location.lat,
            longitude: location.lng,
            street: detail[0].street,
            city: detail[0].city,
            // name: detail[0].name,
            region: detail[0].region,
            postalCode: detail[0].postalCode,
        })
    }

    saveAddress() {

        this.setState({
            spinner: true,
        })
        const navigation = this.props.navigation

        let params = {
            session_id: this.props.session_id,
            address_id: this.props.route.params.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('alertSuccessEditAddressContent')

            )
            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 keyboardShouldPersistTaps='handled'>
                        <View style={styles.content}>
                            <View style={{ 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 }}>
                                    <GooglePlacesAutocomplete
                                        placeholder={i18n.t('findAddress')}
                                        fetchDetails
                                        onPress={(data, details = null) => {
                                            this.onSubmit(details.geometry.location)
                                        }}
                                        textInputProps={{
                                            onChangeText: (address) => { this.setState({ address }) },
                                            onSubmitEditing: () => { this._searchLocation() }
                                        }}
                                        query={{
                                            key: 'AIzaSyCnsGKSJtSNAbVAPX2cSNTQk2L97X7PX68',
                                            language: 'en',
                                            components: 'country:id',
                                        }}
                                        styles={{
                                            textInputContainer: {
                                                backgroundColor: 'rgba(0,0,0,0)',
                                                borderTopWidth: 0,
                                                borderBottomWidth: 0,
                                            },
                                            textInput: {
                                                marginLeft: 0,
                                                marginRight: 0,
                                                height: 30,
                                                color: '#5d5d5d',
                                                fontSize: 14,
                                            },
                                            predefinedPlacesDescription: {
                                                color: '#1faadb',
                                            },
                                        }}
                                    />
                                </View>
                                <View style={{ flex: 1, margin: 5 , display:'none'}} >
                                    <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.001,
                                        longitudeDelta: 0.001,

                                    }}
                                    onPress={(e) => this.onChangeLocation(e)}
                                    zoomEnabled={true}
                                    showsMyLocationButton={true}
                                    loadingEnabled={true}
                                    showsUserLocation={true}
                                    showsScale={true}
                                    provider={PROVIDER_GOOGLE}
                                    zoomControlEnabled={true}
                                    style={styles.cont_google_map}>
                                    <MapView.Marker
                                        draggable
                                        onDragEnd={(e) => this.onChangeLocation(e)}
                                        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: 'red' }} 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('address_name')}</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 })}
                                        // placeholder={this.props.route.params.name}
                                        value={this.state.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('address_fulladdress')}</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 })}
                                        // placeholder={this.props.route.params.address}
                                        value={this.state.description}
                                        numberOfLines={10}
                                        multiline={true}
                                        caretHidden={this.state.caretHidden}
                                        onFocus={() => this.setState({ caretHidden: false })} />

                                    <Text style={{ color: '#666666', textAlign: 'center', fontSize: 14, paddingBottom: 15 }}>{i18n.t('address_fulladdress_helptext')}</Text>
                                </View>
                                <View style={{ margin: 50, justifyContent: 'center' }}>
                                    {
                                        this.state.indicator == true ? (
                                            <View style={{ height: 40, borderRadius: 10, backgroundColor: '#838383', justifyContent: 'center' }}>
                                                <ActivityIndicator size="large" color="#c9af6d" />
                                            </View>
                                        ) : (
                                                <TouchableOpacity onPress={() => this.validation()}>
                                                    <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', justifyContent: 'center' }}>
                                                        <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center' }}>{i18n.t('editaddress')}</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: 350,
    },

    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)(EditAddressDetail)
