import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Alert,
  SafeAreaView
} from "react-native";
import { observable } from "mobx";
import { Button } from "react-native-elements";
import Text from "react-native-text";
import { observer, inject } from "mobx-react/native";
import Header from "../../components/Public/header";
import Toast, { DURATION } from "react-native-easy-toast";
import { width, height } from "../../config/screen";
import FoodsRow from "../../components/MyOrders/foodsRow";
import moment from "moment";
import FoodsRowForOrderDetails from "../../components/MyOrders/foodsRowForOrderDetails";
import Icon from "react-native-vector-icons/dist/MaterialCommunityIcons";
import { scale, verticalScale, moderateScale } from "react-native-size-matters";
import { Dropdown } from "react-native-material-dropdown";
import FastImage from "react-native-fast-image";
import { Popup } from "react-native-map-link";
import theme from "../../config/colors";
import { Fonts } from "../../config/fonts";
import CommonTextView from "../../components/Public/commonTextView";
import Size from "../../config/size";
const size = new Size();

@inject(["menuStore"], ["userStore"])
@observer
export default class OrderDetails extends Component {
  @observable
  buttonColor = theme.mainColor;
  @observable
  buttonDisabled = false;
  @observable
  options = {
    latitude: 38.8976763,
    longitude: -77.0387185,
    title: "",
    dialogTitle: "Select the map",
    dialogMessage: "",
    cancelText: "Cancel"
  };
  timeIndex = null;
  data = {};
  static navigationOptions = {
    drawerLabel: "My Orders"
  };

  constructor(props) {
    super(props);
    this.store = this.props.menuStore;
    this.userStore = this.props.userStore;
    this.state = {
      isVisible: false
    };
  }

  componentWillMount() {
    const { navigation } = this.props;
    this.data = navigation.getParam("data", {});
    this.time = navigation.getParam("time", {});
    //console.log(this.data+" "+this.time);

    this.options.latitude = this.data.pickUpLocation.lat;
    this.options.longitude = this.data.pickUpLocation.lng;
    this.options.title = this.data.pickUpLocation.name;
    this.canCancelOrNot();
  }

  navigatieAction(page) {
    this.props.navigation.navigate(page);
  }

  dateFormat() {
    var momentDate = moment(this.data.items[0].pickupEnd);
    var timestamp = momentDate.toDate();
    var options = {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    };
    return timestamp.toLocaleDateString("En", options);
  }

  pickupTime(){
    var pickupTimeStartString = this.data.items[0].pickupStart.substring(11,16)
    var pickupTimeEndString = this.data.items[0].pickupEnd.substring(11,16)
    return pickupTimeStartString + " - " + pickupTimeEndString
  }

  canCancelOrNot() {
    if (this.data.status != "D") {
      if (this.time) {
        this.buttonColor = theme.inputBgc;
        this.buttonDisabled = true;
      } else {
        console.log('this')
        this.buttonColor = theme.mainColor;
        this.buttonDisabled = false;
      }
    } else {
      this.buttonColor = theme.inputBgc;
      this.buttonDisabled = true;
    }
  }

  renderFoodsList() {
    return this.data.items.map(items => {
      return (
        <FoodsRowForOrderDetails
          items={items}
          key={items.id}
          lang={this.userStore.languageSelection}
        />
      );
    });
  }
  back() {
    this.props.navigation.goBack();
  }

  goLocationAction() {
    this.props.navigation.navigate("Location", {
      location: {
        latitude: this.data.pickUpLocation.lat,
        longitude: this.data.pickUpLocation.lng
      }
    });
  }

  discountText() {
    if (this.data.discount > 0) {
      return (
        <Text
          style={{
            color: theme.coolGrey,
            fontFamily: Fonts.century,
            fontWeight: "bold",
            fontSize: 10
          }}
        >
        {"- "+this.data.discount}
        </Text>
      );
    }
  }

  cancelAction() {}

  cancelOrderAlert() {
    Alert.alert("", "Are you sure to cancel this order?", [
      { text: "Cancel", onPress: () => console.log("Cancel") },
      { text: "Cancel order", onPress: () => this.cancelOrder() }
    ]);
  }

  cancelOrder() {
    var token = this.userStore.userData.data.token;
    this.store.voidOrder(token, this.data.id, this);
  }

  render() {
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: theme.mainColor }}>
        <View style={styles.container}>
          <View style={{ width: width, marginTop: 15 }}>
            <Icon
              name="chevron-left"
              size={size.getSize(40)}
              color={theme.foodNameColor}
              style={{ marginLeft: 10 }}
              onPress={() => this.back()}
            />
          </View>
          <ScrollView style={{ width: width, flex: 1 }}>
            <View style={{ marginRight: 20, marginLeft: 20 }}>
              {this.renderFoodsList()}
              {this.discountText()}
              <View
                style={{
                  flexDirection: "row",
                  marginTop: 10,
                  marginBottom: 10,
                  marginLeft: 5,
                  marginRight: 5,
                  alignItems: "center",
                  justifyContent: "space-between"
                }}
              >
                <Text
                  style={{
                    color: theme.coolGrey,
                    fontFamily: Fonts.century,
                    fontWeight: "bold",
                    fontSize:15,
                  }}
                >
                  TOTAL
                </Text>
                <View
                  style={{ flexDirection: "row", justifyContent: "flex-end" }}
                >
                  <Text
                    style={{
                      color: theme.coolGrey,
                      fontFamily: Fonts.century,
                      fontWeight: "bold",
                      fontSize:15
                    }}
                  >
                    HKD ${this.data.payAmount.toFixed(2)}
                  </Text>
                </View>
              </View>

              <Text
                style={{
                  fontSize: 10,
                  color: theme.coolGrey,
                  fontFamily: Fonts.century,
                  fontWeight: "bold",
                  fontSize:15
                }}
              >
                Delivery Details
              </Text>
              <View>
                <CommonTextView
                  title="Pickup Date"
                  content={this.dateFormat()}
                />
                <TouchableOpacity
                  onPress={() => {
                    this.setState({ isVisible: true });
                  }}
                >
                  <CommonTextView
                    title="Pickup Location"
                    content={this.userStore.dataLanguage(
                      this.data.pickUpLocation,
                      "name"
                    )}
                  />
                </TouchableOpacity>

                <CommonTextView
                  title="Pickup Time"
                  content={
                   this.pickupTime()
                  }
                />
              </View>

              <View
                style={{
                  borderBottomColor: "black",
                  borderBottomWidth: 1,
                  marginTop: 15,
                  marginBottom: 10,
                  width: "70%"
                }}
              >
                <Text
                  style={{
                    color: theme.coolGrey,
                    fontFamily: Fonts.century,
                    fontSize: 13
                  }}
                >
                  Mobile phone
                </Text>
                <Text
                  style={{
                    width: "60%",
                    color: theme.coolGrey,
                    fontSize: 13
                  }}
                >
                  {this.data.mobile}
                </Text>
              </View>

              <FastImage
                style={{
                  width: width - 40,
                  marginTop: 15,
                  marginBottom: 15,
                  height: verticalScale(200),
                  backgroundColor: theme.mainColor
                }}
                source={{
                  uri: this.data.pickUpLocation.photo
                }}
              />

              <Text
                style={{
                  marginTop: 15,
                  marginBottom: 5,
                  fontSize: 13,
                  color: theme.coolGrey,
                  fontFamily: Fonts.century
                }}
              >
                Message box
              </Text>
              <Text
                style={{
                  // backgroundColor:theme.inputBgc,
                  color: theme.foodNameColor,
                  width: width - 40,
                  height: verticalScale(100),
                  marginBottom: 20,
                  paddingBottom: 0,
                  paddingRight: 5,
                  paddingLeft: 5,
                  fontSize: 13,
                  fontFamily: Fonts.century,
                  borderColor: theme.foodNameColor,
                  borderWidth: 1,
                  borderRadius: 5
                }}
              >
                {this.data.remark}
              </Text>
            </View>
          </ScrollView>
          <Button
            title="Cancel order"
            fontWeight="bold"
            disabled={ this.buttonDisabled}
            fontSize={size.getSize(15)}
            fontFamily={Fonts.century}
            titleStyle={{
              color: "white",
              fontFamily: Fonts.century,
              fontWeight: "bold"
            }}
            loadingProps={{
              size: "large",
              color: "rgba(111, 202, 186, 1)"
            }}
            buttonStyle={{
              width: width,
              height: verticalScale(50),
              backgroundColor: this.buttonColor
            }}
            onPress={() => this.cancelOrderAlert()}
          />

          <Toast ref="toast" />
        </View>
        <Popup
          isVisible={this.state.isVisible}
          onCancelPressed={() => this.setState({ isVisible: false })}
          onAppPressed={() => this.setState({ isVisible: false })}
          onBackButtonPressed={() => this.setState({ isVisible: false })}
          options={this.options}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "white"
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 10
  },
  instructions: {
    textAlign: "center",
    color: "#333333",
    marginBottom: 5
  },
  signupButton: {
    width: width,
    height: verticalScale(50),
    backgroundColor: theme.mainColor
  }
});
