<template>
  <div v-if="userDetails">
    <v-form ref="shippingAddressform" v-model="valid" :lazy-validation="lazy">
      <v-row no-gutters v-if="!this.userAuth">
        <v-col cols="12">
          <p class="text-uppercase">
            already registered?
            <span class="text-uppercase ml-2">click here to login</span>
          </p>
          <v-text-field label="Email Address" ref="emailAddress" outlined dense :rules="emailRules"></v-text-field>
          <span>You can create an account after checkout.</span>
          <v-checkbox v-model="newsletter" label="Subscribe to our newsletter" color="indigo"></v-checkbox>
        </v-col>
      </v-row>
      <v-row no-gutters>
        <v-col cols="12">
          <v-text-field
            label="First Name"
            ref="firstName"
            v-model="firstname"
            outlined
            dense
            :rules="hideAndShowFields? textRules:[]"
            v-show="hideAndShowFields"
            @input="verifyAddress"
          ></v-text-field>
          <v-text-field
            label="Last Name"
            ref="lastName"
            v-model="lastname"
            outlined
            dense
            :rules="hideAndShowFields? textRules:[]"
            v-show="hideAndShowFields"
            @input="verifyAddress"
          ></v-text-field>
          <v-text-field
            label="Street Address"
            ref="streetAddressOne"
            v-model="streetNoOne"
            outlined
            dense
            required
            :rules="textRules"
            @input="verifyAddress"
            @change="checkPOBoxAddress()"
          ></v-text-field>
          <v-text-field
            label="Apt, Suite, Co., C/O etc."
            ref="streetAddressTwo"
            v-model="streetNoTwo"
            outlined
            dense
            required
            @change="checkPOBoxAddress()"
            @input="verifyAddress"
          ></v-text-field>
          <v-text-field
            label="City"
            outlined
            dense
            ref="city"
            :rules="textRules"
            v-model="city"
            @input="verifyAddress"
          ></v-text-field>
          <v-select
            :items="allCountries"
            dense
            outlined
            label="Country"
            ref="country"
            item-text="label"
            v-model="countryId"
            item-value="value"
            :selected="countryId"
            @change="fetchStates(countryId)"
            :rules="[val => !!val || 'Please select the Country']"
          ></v-select>
          <v-text-field
            label="Zip/Postal Code"
            ref="zipCode"
            :rules="zipCodeRules"
            v-model="postcode"
            outlined
            dense
            @input="verifyAddress"
          ></v-text-field>
          <!-- <v-alert type="error" v-if="zipCodeRules">{{zipCodeValidation}}</v-alert> -->
          <v-select
            :items="regionList"
            dense
            label="State/Province"
            v-model="regionId"
            item-text="label"
            item-value="value"
            outlined
            @change="checkRegionName()"
            :rules="[v => !!v || 'Please select the State']"
          ></v-select>
          <vue-tel-input
            type="number"
            v-model="telephone"
            :defaultCountry="setCountryCode"
            :class="phoneNumberError ?  'phonenumber-input-error-border':'phonenumber-custom-input'"
            @input="validateNumber"
            ref="phoneNumber"
            v-show="hideAndShowFields"
          ></vue-tel-input>
          <span class="red--text caption ml-3" v-show="phoneNumberError">This field is required</span>
        </v-col>
      </v-row>
    </v-form>
  </div>
</template>
<script>
//import { mapState } from "vuex";
import { createHelpers } from "vuex-map-fields";
import { fetchStates } from "@/services/util.service";
import { VueTelInput } from "vue-tel-input";

const { mapFields } = createHelpers({
  getterType: "accountOne/getField",
  mutationType: "accountOne/updateField"
});
export default {
  name: "ShippingAddressFormComponent",
  props: ["hideAndShowFields"],
  data: () => ({
    setCountryCode: "US",
    phoneNumberError: false,
    confirmationDialog: false,
    newsletter: false,
    regionList: [],
    userDetails: true,
    c: "",
    valid: true,
    lazy: false,
    textRules: [
      v => !!v || "This field is required",
      v => (v && v.length >= 3) || "This field must be at least 3 characters"
    ],
    zipCodeRules: [
      v => !!v || "Zip code is required",
      v => (v && v.length >= 5) || "This field must be at least 5 characters"
    ],
    emailRules: [
      v => !!v || "E-mail is required",
      v => /.+@.+\..+/.test(v) || "E-mail must be valid"
    ],
    phoneNumberRules: [
      v => !!v || "This field is required",
      v => (v && v.length >= 8) || "Phone Number must be at least 8 characters"
    ]
  }),
  components: {
    VueTelInput
  },
  computed: {
    ...mapFields([
      "one",
      // "one.firstname",
      // "one.lastname",
      "address",
      "address.postcode",
      "address.telephone",
      "address.city",
      "address.countryId",
      "address.regionId",
      "address.region",
      "address.streetNoOne",
      "address.streetNoTwo",
      "address.firstname",
      "address.lastname"
    ]),
    allCountries: function() {
      return this.$store.state.accountOne.allCountries.map(countries => {
        return {
          value: countries.id,
          label: countries.fullNameEnglish
        };
      });
    },
    add: function() {
      return this.$store.state.accountOne.address;
    },
    countryAndStatesList() {
      return this.$store.state.accountOne.allCountries;
    },
    userAuth: function() {
      return this.$store.state.auth.userAuth;
    }
  },
  watch: {
    /*countryId: function() {
      this.updateRegionList();
    },*/
    regionId: function() {
      this.fetchStates(this.countryId);
    },
    valid() {
      this.$emit("actionValid", this.valid);
    }
  },
  methods: {
    verifyAddress() {
      this.$emit("verifyAddress");
    },
    checkRegionName() {
      if (this.regionId) {
        this.regionId = this.regionId.toString();

        let regionName = this.regionList.filter(obj => {
          if (obj.value == this.regionId) return obj;
        });
        this.$emit("regionDetails", regionName);
        this.$emit("verifyAddress");
      }
    },
    fetchStates(countryId) {
      /*eslint-disable*/
      // this.$refs.shippingAddressform.resetValidation();
      this.regionList = fetchStates(countryId, this.countryAndStatesList);
      this.regionId = this.regionId ? this.regionId.toString(): '';
      if (this.regionId) {
        let regionName = this.regionList.filter(obj => {
          if (obj.value == this.regionId) return obj;
        });
        this.$emit("regionDetails", regionName);
        this.$emit("verifyAddress");
      }
      /*let base = this.countryAndStatesList.filter(states => {
        return states.id == id;
      });
      if (base.length > 0) {
        this.region = base[0].availableRegions.map(val => {
          return {
            value: val.id,
            label: val.name
          };
        });
      }*/
    },
    updateRegionList() {
      if (this.regionId) {
        this.regionId = this.regionId.toString();
      }
      this.regionList = fetchStates(this.countryId, this.countryAndStatesList);
    },
    validateNumber(number, data) {
      if (data&&data.possible && data.valid) this.phoneNumberError = false;
      else this.phoneNumberError = true;
    },
    async checkPOBoxAddress(){
      let street = [];
      street[0] = this.streetNoOne ? this.streetNoOne : "";
      if(this.streetNoTwo)
        street[1] = this.streetNoTwo ? this.streetNoTwo : "";
      let address = {
        street: street
      }
      await this.$store.dispatch("accountOne/checkPOBoxAddress", address);
    }
  },
  async created() {
    await this.$store.dispatch("accountOne/fetchCountries");
    //this.updateRegionList();
    await this.fetchStates(this.countryId);
    this.checkRegionName();
    if (this.$refs.shippingAddressform)
      this.$refs.shippingAddressform.resetValidation();
    if (this.valid) {
      this.$emit("actionValid", this.valid);
      this.$emit("verifyAddress");
    }
  }
};
</script>
