import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  Alert,
  NetInfo,
  Geolocation,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  Image,
  TouchableHighlight
} from "react-native";
import Header from "../../components/Public/header";
import Text from "react-native-text";
import { SearchBar } from "react-native-elements";
import { observer, inject } from "mobx-react/native";
import { observable, transaction } from "mobx";
import { scale, verticalScale, moderateScale } from "react-native-size-matters";
import { width, height } from "../../config/screen";
import Permissions from "react-native-permissions";
import MapView, { Polyline } from "react-native-maps";
import MapViewDirections from "react-native-maps-directions";
import AsyncStorageHelper from "../../config/asyncStorageHelper";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import theme from "../../config/colors";
import MyStatusBar from "../../components/Public/statusBar";
const asyncStorageHelper = new AsyncStorageHelper();
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
const origin = { latitude: 22.320508, longitude: 114.170222 };
const destination = { latitude: 22.320568, longitude: 114.171273 };
const GOOGLE_MAPS_APIKEY = "AIzaSyB_9Wi7BcAgqMPxZvW_5DWb8UxF5W9tWz0";

@inject(["menuStore"], ["userStore"])
@observer
export default class Map extends Component {
  @observable
  markerId = null;
  @observable
  region = {
    latitude: 22.396427,
    longitude: 114.109497,
    latitudeDelta: 1,
    longitudeDelta: 1
  };

  constructor(props) {
    super(props);
    this.store = this.props.menuStore;
    this.userStore = this.props.userStore;
    this.state = {
      region: {
        latitude: null,
        longitude: null,
        latitudeDelta: 1,
        longitudeDelta: 1
      }
    };
  }

  _requestPermission() {
    Permissions.request("location").then(response => {
      // Returns once the user has chosen to 'allow' or to 'not allow' access
      // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
      // this.setState({ photoPermission: response })
      if (
        response == "allow" ||
        response == "restricted" ||
        response == "authorized"
      ) {
        navigator.geolocation.getCurrentPosition(
          position => {
            console.log(position.coords.latitude);
            this.map.animateToRegion({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
              latitudeDelta: 0.02,
              longitudeDelta: 0.02
            });
          },
          error => {
            console.log(error);

            this.region = {
              latitude: 22.396427,
              longitude: 114.109497,
              latitudeDelta: 1,
              longitudeDelta: 1
            };
          },
          { enableHighAccuracy: false, timeout: 4000, maximumAge: 10000 }
        );
      } else {
        this.region = {
          latitude: 22.396427,
          longitude: 114.109497,
          latitudeDelta: 1,
          longitudeDelta: 1
        };
      }
    });
  }

  goPosition(data, details) {
    this.map.animateToRegion({
      latitude: details.geometry.location.lat,
      longitude: details.geometry.location.lng,
      latitudeDelta: 0.02,
      longitudeDelta: 0.02
    });

    for (var i = 0; i < this.props.perfdefinedPlaces.length; i++) {
      if (
        this.props.perfdefinedPlaces[i].geometry.location.lat ==
          details.geometry.location.lat &&
        this.props.perfdefinedPlaces[i].geometry.location.lng ==
          details.geometry.location.lng
      ) {
        this.markerId = this.props.perfdefinedPlaces[i].id
        break;
      }
    }

    console.log(details);
  }

  clickMarkerAction(id) {
    this.markerId = id;
    this.store.pickupPointId = id;
    this.userStore.pickupPointId = id;
  }
  picked(id) {
    asyncStorageHelper.saveData("pickupPointId", id);
    this.store.getMenuItem(this);
    //this.props.navigation.navigate('menu')
  }
  confirmButton() {
    if (!this.markerId) {
      return null;
    } else {
      return (
        <TouchableHighlight
          style={{
            height: verticalScale(60),
            width: width,
            backgroundColor: theme.mainColor,
            alignItems: "center",
            justifyContent: "center"
          }}
          onPress={() => {
            this.props.onPress && this.props.onPress(this.markerId);
          }}
        >
          <Text style={{ color: "white", fontWeight: "bold" }}>
            {this.userStore.text.confirm}
          </Text>
        </TouchableHighlight>
      );
    }
  }

  componentWillMount() {
    this.setUserLocation();
    this._requestPermission();
    if (this.props.onRef) {
      this.props.onRef(undefined);
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  setUserLocation() {
    console.log(this.userStore.userLocation);
    if (this.userStore.userLocation === null) {
      this.setState({
        region: {
          latitude: 22.396427,
          longitude: 114.109497,
          latitudeDelta: 1,
          longitudeDelta: 1
        }
      });
    } else {
      this.setState({
        region: {
          latitude: this.userStore.userLocation.coords.latitude,
          longitude: this.userStore.userLocation.coords.longitude,

          latitudeDelta: 0.02,
          longitudeDelta: 0.02
        }
      });
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <MapView
          ref={ref => {
            this.map = ref;
          }}
          style={{ width: width, flex: 1 }}
          showsUserLocation={true}
          initialRegion={this.region}
        >
          {this.userStore.pickupPointLabel.map(marker => (
            <MapView.Marker
              coordinate={{ latitude: marker.lat, longitude: marker.lng }}
              title={marker.name}
              onPress={() => this.clickMarkerAction(marker.id)}
            >
              <Image
                resizeMode={"contain"}
                source={require("../../images/maplocator.png")}
                style={{ width: scale(50), height: scale(50) }}
              />
            </MapView.Marker>
          ))}
        </MapView>

        {this.confirmButton()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  }
});
