import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  SafeAreaView,
  TextInput,
  Alert
} from "react-native";
import { observable } from "mobx";
import Text from "react-native-text";
import { Button } from "react-native-elements";
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 FastImage from "react-native-fast-image";
import Icon from "react-native-vector-icons/dist/MaterialCommunityIcons";
import Log from "../../config/log";
import Size from "../../config/size";
import { scale, verticalScale, moderateScale } from "react-native-size-matters";
import { Dropdown } from "react-native-material-dropdown";
import CommonTextView from "../../components/Public/commonTextView";
import theme from "../../config/colors";
import Loader from "../../components/Public/loader";
import { Popup } from "react-native-map-link";
import { Fonts } from "../../config/fonts";
import { colors } from "react-native-elements";
const size = new Size();
const log = new Log();
const time = [
  {
    value: "12:10 - 12:40",
    format: "12101240"
  },
  {
    value: "13:10 - 13:40",
    format: "13101340"
  },
  {
    value: "14:10 - 14:40",
    format: "14101440"
  }
];

@inject(["menuStore"], ["userStore"])
@observer
export default class ConfirmOrder extends Component {
  @observable
  message = "";
  @observable
  tel = "1234556";
  @observable
  pomoCode = "";
  @observable
  total = 0;
  @observable
  discount = 0;
  @observable
  subVaule = 0;
  @observable
  options = {
    latitude: 38.8976763,
    longitude: -77.0387185,
    title: "",
    dialogTitle: "Select the map",
    dialogMessage: "",
    cancelText: "Cancel"
  };
  timeIndex = null;
  couponLabel = [];
  static navigationOptions = {
    drawerLabel: "My Orders"
  };

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

  componentDidMount() {
    log.firebaseClass("ConfirmOrder");
    this.total = this.store.totalMoney.toFixed(2);
    this.tel = this.userStore.userData.data.member.mobile;
    console.log(this.store.couponLabel);
  }

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

  renderFoodsList() {
    return this.store.orderList.map(items => {
      console.log(items.cuisine.nameEn);
      return (
        <FoodsRow
          items={items}
          key={items.id}
          lang={this.userStore.languageSelection}
        />
      );
    });
  }

  dateFormat() {
    var cutoffDate = this.store.cutoffDateTime;
    console.log(this.store.cutoffDateTime);
    var today = new Date();
    var tomorrowOrToday = "";
    if (today.getUTCDate() == cutoffDate.getUTCDate()) {
      var tomorrowOrToday = "(Today)";
    }
    var options = {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric"
    };
    return cutoffDate.toLocaleDateString("En", options) + tomorrowOrToday;
  }

  discountText() {
    if (this.discount > 0) {
      return (
        <Text
          style={{
            color: theme.coolGrey,
            fontFamily: Fonts.century,
            fontWeight: "bold",
            fontSize: 13
          }}
        >
          Discount {this.discount + "%" + " off"}
        </Text>
      );
    } else if (this.subVaule > 0) {
      return (
        <Text
          style={{
            color: theme.coolGrey,
            fontFamily: Fonts.century,
            fontWeight: "bold",
            fontSize: 13
          }}
        >
          Total {"- " + this.subVaule}
        </Text>
      );
    }
  }

  orderAction() {
    var today = new Date();
    yymmdd =
      today.getFullYear() +
      "-" +
      ("0" + (today.getMonth() + 1)).slice(-2) +
      "-" +
      ("0" + (today.getDay() + 1)).slice(-2);
    console.log(yymmdd);
    var token = this.userStore.userData.data.token;
    console.log(token);
    var orderData = {
      pickUpLocation: {
        id: this.userStore.pickupPointId
      },
      // "pickUpDate": yymmdd,
      // "pickUpTime": time[this.timeIndex].format,
      items: this.store.items,
      coupon: this.pomoCode,
      mobile: this.tel,
      remark: this.message
    };
    console.log(orderData);
    this.store.order(token, orderData, this);
  }
  onChangeText(text) {
    this.pomoCode = text;
    this.pressYeahButton();
  }

  pay() {
    this.store.loading = false;
    Alert.alert("", "Pay now? ", [
      {
        text: "Cancel",
        onPress: () => {
          log.firebaseLog("press_cancel_button_on_confirmOrder", {}),
            this.store.cancelOrder(this.userStore.userData.data.token);
        }
      },
      {
        text: "Pay",
        onPress: () => {
          log.firebaseLog("press_pay_button_on_confirmOrder", {}),
            this.store.pay(
              this.userStore.userData.data.token,
              this,
              this.userStore.creditCardinfo.id
            );
        }
      }
    ]);
  }
  // type 0 all user can use, type 1 all user can use once

  discountAction(data) {
    if (data.value == 0) {
      this.discount = data.percent;
      if (this.discount == null || this.discount == 0) {
        this.total = this.store.totalMoney.toFixed(2);
      } else {
        var total = (this.store.totalMoney * (100 - this.discount)) / 100;
        this.total = total.toFixed(2);
      }
    } else {
      this.subVaule = data.value;
      if (this.subVaule == null || this.subVaule == 0) {
        this.total = this.store.totalMoney.toFixed(2);
      } else {
        var total = this.store.totalMoney - this.subVaule;
        this.total = total.toFixed(2);
      }
    }
  }

  pressYeahButton() {
    log.firebaseLog("press_yeah_button_on_confirmOrder", {}),
      this.store.coupon(
        this.userStore.userData.data.token,
        this,
        this.pomoCode
      );
    this.subVaule = 0;
    this.discount = 0;
  }

  back() {
    this.props.navigation.goBack();
  }

  render() {
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: theme.mainColor }}>
        <Loader loading={this.store.loading} />
        <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()}

              <View
                style={{
                  flexDirection: "row",
                  marginTop: 10,
                  marginBottom: 10,
                  marginLeft: 5,
                  marginRight: 5,
                  alignItems: "flex-start",
                  justifyContent: "space-between"
                }}
              >
                <View style={{ flexDirection: "row" }}>
                  <Image
                    resizeMode={"contain"}
                    source={require("../../images/promo.png")}
                  />
                  <View>
                    <View
                      style={{
                        backgroundColor: theme.inputBgc,
                        justifyContent: "center",
                        alignItems: "center",
                        width: 110,
                        height: 20,
                        marginLeft: 5
                      }}
                    >
                      <TextInput
                        style={{
                          width: 100,
                          color: theme.coolGrey,
                          ...Platform.select({
                            ios: {
                              height: 20
                            },
                            android: {
                              paddingBottom: 5,
                              height: 30
                            }
                          })
                        }}
                        value={this.pomoCode}
                        underlineColorAndroid="rgba(0,0,0,0)"
                        onChangeText={text => (this.pomoCode = text)}
                        placeholder={"Promo Code"}
                        placeholderStyle={{
                          fontWeight: "bold",
                          fontFamily: Fonts.century
                        }}
                        placeholderTextColor={theme.coolGrey}
                      />
                    </View>
                    <View style={{ marginLeft: 5, marginTop: -5 }}>
                      <Dropdown
                        label={this.userStore.text.coupon}
                        onChangeText={text => {
                          this.onChangeText(text);
                        }}
                        data={this.store.couponLabel}
                        fontSize={12}
                      />
                    </View>
                  </View>
                </View>

                <TouchableOpacity
                  style={{
                    backgroundColor: theme.mainColor,
                    height: 20,
                    width: 60,
                    alignItems: "center",
                    justifyContent: "center"
                  }}
                  onPress={() => {
                    this.pressYeahButton();
                  }}
                >
                  <Text
                    style={{
                      fontFamily: Fonts.century,
                      color: "white",
                      fontSize: 13,
                      fontWeight: "bold"
                    }}
                  >
                    Yeah
                  </Text>
                </TouchableOpacity>
              </View>

              {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.total}
                  </Text>
                </View>
              </View>

              <Text
                style={{
                  fontSize: 13,
                  color: theme.coolGrey,
                  fontFamily: Fonts.century,
                  fontWeight: "bold"
                }}
              >
                Delivery Details
              </Text>
              <View>
                <CommonTextView
                  title="Pickup Date"
                  content={this.dateFormat()}
                />
                <TouchableOpacity
                  onPress={() => {
                    this.options.latitude = this.userStore.pickupPointLabel[
                      this.userStore.pickupIndex
                    ].lat;
                    this.options.longitude = this.userStore.pickupPointLabel[
                      this.userStore.pickupIndex
                    ].lng;
                    this.setState({ isVisible: true });
                  }}
                >
                  <CommonTextView
                    title="Pickup Location"
                    content={this.userStore.dataLanguage(
                      this.userStore.pickupPointLabel[
                        this.userStore.pickupIndex
                      ],
                      "name"
                    )}
                  />
                </TouchableOpacity>

                <CommonTextView
                  title="Pickup Time"
                  content={
                    this.userStore.pickupPointLabel[this.userStore.pickupIndex]
                      .pickupStartTime +
                    " - " +
                    this.userStore.pickupPointLabel[this.userStore.pickupIndex]
                      .pickupEndTime
                  }
                />
              </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>
                <TextInput
                  style={{
                    width: "60%",
                    color: theme.coolGrey,
                    fontSize: size.getSize(13),
                    paddingVertical: 0
                  }}
                  value={this.tel}
                  keyboardType={"numeric"}
                  underlineColorAndroid="rgba(0,0,0,0)"
                  onChangeText={tel => (this.tel = tel)}
                />
              </View>

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

              <Text
                style={{
                  marginTop: 15,
                  marginBottom: 5,
                  fontSize: 13,
                  color: theme.coolGrey,
                  fontFamily: Fonts.century
                }}
              >
                Message box
              </Text>
              <TextInput
                style={{
                  // backgroundColor:theme.inputBgc,
                  color: theme.foodNameColor,
                  width: width - 40,
                  height: verticalScale(100),
                  marginBottom: 20,
                  paddingBottom: 0,
                  paddingRight: 5,
                  paddingLeft: 5,
                  fontSize: size.getSize(13),
                  fontFamily: Fonts.century,
                  borderColor: theme.foodNameColor,
                  borderWidth: 1,
                  borderRadius: 5,
                  paddingVertical: 0
                }}
                multiline={true}
                value={this.message}
                underlineColorAndroid="rgba(0,0,0,0)"
                onChangeText={text => (this.message = text)}
                placeholder={"Tell me any requires"}
                placeholderStyle={{
                  fontWeight: "bold",
                  fontFamily: Fonts.century
                }}
                placeholderTextColor={theme.foodNameColor}
              />
            </View>
          </ScrollView>
          <Button
            title="confirm order"
            fontWeight="bold"
            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={styles.signupButton}
            onPress={() => this.orderAction()}
          />

          <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
  }
});
