<template>
  <v-container>
    <v-row>
      <v-col cols="12" sm="12" class="fontcolor-black-light">
        <div v-show="!addressId">
          <p class="h2 mb-5 body-font text-uppercase text-primary pb-2">
            Address Book
          </p>
          <div class="address-book-line my-1"></div>
          <v-row
            class="mt-12"
            align="center"
            justify="center"
            v-if="inProgress"
          >
            <v-progress-circular
              :size="60"
              color="primary"
              indeterminate
            ></v-progress-circular>
          </v-row>
          <v-row class="mt-4" v-else>
            <v-col cols="12" sm="6" md="6" lg="6">
              <p class="body-font text-uppercase text-primary font-weight-bold">
                Default Billing Address
              </p>
              <p class="body-font" v-if="!billingAddressDetails.address">
                You have not set a default billing address.
              </p>
              <div v-else>
                <p class="body-font">You have set a default billing address.</p>
                <BillingAddressComponent
                  :address="billingAddressDetails.address"
                />
              </div>
              <v-row>
                <v-col cols="12">
                  <v-hover v-slot:default="{ isHovering, props }">
                    <v-btn
                      @click="
                        editAddress(
                          billingAddressDetails.address,
                          billingAddressDetails.index
                        )
                      "
                      v-bind="props"
                      :variant="isHovering ? 'outlined' : 'outlined'"
                      :class="
                        isHovering ? ' bg-white text-primary' : 'bg-primary'
                      "
                      rounded="0"
                      size="large"
                      :large="$vuetify.display.mdAndUp ? true : false"
                      class="body-font my-2 address-book-button"
                      >EDIT</v-btn
                    >
                  </v-hover>
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" sm="6" md="6" lg="6">
              <p class="body-font text-uppercase text-primary font-weight-bold">
                Default Shipping Address
              </p>
              <p class="body-font" v-if="!shippingAddressDetails.address">
                You have not set a default shipping address.
              </p>
              <div v-else>
                <p class="body-font">
                  You have set a default shipping address.
                </p>
                <ShippingAddressComponent
                  :address="shippingAddressDetails.address"
                />
              </div>
              <v-row>
                <v-col cols="12">
                  <v-hover v-slot:default="{ isHovering, props }">
                    <v-btn
                      @click="
                        editAddress(
                          shippingAddressDetails.address,
                          shippingAddressDetails.index
                        )
                      "
                      :large="$vuetify.display.mdAndUp ? true : false"
                      v-bind="props"
                      :variant="isHovering ? 'outlined' : 'outlined'"
                      :class="
                        isHovering ? ' bg-white text-primary' : 'bg-primary'
                      "
                      rounded="0"
                      size="large"
                      class="body-font my-2 address-book-button"
                      >EDIT</v-btn
                    >
                  </v-hover>
                </v-col>
              </v-row>
            </v-col>
          </v-row>
          <div>
            <v-col>
              <v-row class="mt-4">
                <p
                  class="h3 body-font text-uppercase text-primary pb-2 mb-1 mr-3"
                >
                  Additional Address Entries
                </p>
              </v-row>
            </v-col>
            <div class="address-book-line my-1"></div>
            <v-row
              class="mt-12"
              justify="center"
              align="center"
              v-if="fetchInProgress"
            >
              <v-progress-circular
                :size="60"
                color="primary"
                indeterminate
              ></v-progress-circular>
            </v-row>
            <v-row
              v-else-if="
                addresses.length < 2 &&
                address.id == basicInfo.defaultBilling &&
                address.id == basicInfo.defaultShipping
              "
            >
              <v-col>
                <p class="body-font mb-1 mr-3">
                  You have no other address entries in your address book.
                </p>
              </v-col>
            </v-row>
            <v-row v-else>
              <v-col
                cols="12"
                sm="6"
                md="6"
                lg="6"
                v-for="(address, index) in addresses"
                v-bind:key="index"
                v-show="
                  address.id !== basicInfo.defaultBilling ||
                  address.id !== basicInfo.defaultShipping
                "
              >
                <ShippingAddressComponent :address="address" />
                <v-row>
                  <v-col cols="2">
                    <v-hover v-slot:default="{ isHovering, props }">
                      <v-btn
                        @click="editAddress(address, index)"
                        v-bind="props"
                        variant="isHovering ? 'outlined' : 'outlined'"
                        :class="
                          isHovering ? ' bg-white text-primary' : 'bg-primary'
                        "
                        rounded="0"
                        size="large"
                        class="body-font my-2 address-book-button"
                        >EDIT</v-btn
                      >
                    </v-hover>
                  </v-col>
                  <v-col cols="2">
                    <v-hover v-slot:default="{ isHovering, props }">
                      <v-btn
                        @click="deleteAddress(address)"
                        v-bind="props"
                        :variant="isHovering ? 'outlined' : 'outlined'"
                        :class="
                          isHovering ? ' bg-white text-primary' : 'bg-primary'
                        "
                        rounded="0"
                        size="large"
                        class="body-font my-2 white--text"
                        >DELETE</v-btn
                      >
                    </v-hover>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
            <v-row>
              <v-col>
                <v-hover v-slot:default="{ isHovering, props }">
                  <v-btn
                    @click="editAddress()"
                    :large="$vuetify.display.mdAndUp ? true : false"
                    v-bind="props"
                    :variant="isHovering ? 'outlined' : 'outlined'"
                    :class="
                      isHovering ? ' bg-white text-primary' : 'bg-primary'
                    "
                    rounded="0"
                    size="large"
                    class="body-font my-2 address-book-button"
                    >ADD NEW ADDRESS</v-btn
                  >
                </v-hover>
              </v-col>
            </v-row>
          </div>
        </div>
        <div v-show="addressId">
          <p class="h2 mb-5 body-font text-uppercase text-primary">
            Add New Address
          </p>
          <v-form ref="addressBookForm" v-model="valid">
            <v-row>
              <v-col cols="12" sm="6">
                <p class="h3 body-font text-uppercase text-primary">
                  Contact Information
                </p>
                <div class="address-book-line mb-5"></div>
                <!-- <ContactInfoComponent v-bind:contactDetails="basicInfo" ref="contactInfoForm" /> -->
                <v-form
                  ref="contactForm"
                  v-model="valid"
                  :lazy-validation="lazy"
                >
                  <v-row no-gutters>
                    <v-col cols="12">
                      <v-text-field
                        label="First Name"
                        ref="firstName"
                        v-model="firstname"
                        color="primary"
                        density="compact"
                        variant="outlined"
                        :rules="textRules"
                        ></v-text-field>
                        <v-text-field
                        label="Last Name"
                        ref="lastName"
                        v-model="lastname"
                       color="primary"
                       density="compact"
                       variant="outlined"
                        required
                        :rules="textRules"
                        ></v-text-field>
                        <v-text-field
                        label="Company"
                        ref="company"
                        v-model="company"
                        color="primary"
                        density="compact"
                        variant="outlined"
                         ></v-text-field>
                        <vue-tel-input
                        type="number"
                        v-model="telephone"
                        :defaultCountry="setCountryCode"
                        :class="
                          phoneNumberError
                            ? 'phonenumber-input-error-border'
                            : 'phonenumber-custom-input'
                        "
                        @input="validateNumber"
                        ></vue-tel-input>
                       <span
                        class="red--text caption ml-3"
                        v-show="phoneNumberError"
                        >This field is required</span
                      >
                    </v-col>
                  </v-row>
                </v-form>
              </v-col>
              <v-col cols="12" sm="6">
                <p class="h3 body-font text-uppercase text-primary">
                  Contact Information
                </p>
                <div class="address-book-line mb-5"></div>

                <ShippingAddressFormComponent
                  :hideAndShowFields="hideAndShowFields"
                  :userDetails="basicInfo.addresses"
                  :allCountries="allCountries"
                  :countryAllStates="countryAllStates"
                  ref="addressForm"
                />
                <v-checkbox
                  v-if="addressId != basicInfo.defaultBilling"
                  v-model="defaultBilling"
                  class="pt-2"
                  label="Use as my default billing address"
                   color="primary"
                ></v-checkbox>
                <v-alert
                  class="alert-box-outline"
                  type="warning"
                  text
                  dense
                  v-if="addressId == basicInfo.defaultBilling"
                  
                  >This is default billing address</v-alert
                >
                <v-checkbox
                  v-if="addressId != basicInfo.defaultShipping"
                  v-model="defaultShipping"
                  class="mt-0"
                  label="Use as my default shipping address"
                   color="primary"
                ></v-checkbox>
                <v-alert
                  class="alert-box-outline"
                  type="warning"
                  text
                  dense
                  v-if="addressId == basicInfo.defaultShipping"
                  >This is default shipping address</v-alert
                >
              </v-col>
            </v-row>
            <v-hover v-slot:default="{ isHovering, props }">
              <v-btn
                v-bind="props"
                class="text-uppercase address-book-button"
                :variant="isHovering ? 'outlined' : 'outlined'"
                :class="isHovering ? ' bg-white text-primary' : 'bg-primary'"
                rounded="0"
                size="large"
                @click.stop="dialog = dialog"
                @click="submit()"
                >SAVE ADDRESS</v-btn
              >
            </v-hover>
            <v-dialog v-model="dialog" persistent max-width="1100px">
              <v-card class="pb-2">
                <v-card-title class="pb-2">
                  <v-row no-gutters>
                    <v-col cols="11">
                      <p class="h2 mb-1 body-font text-uppercase primary--text">
                        Verify Your Address
                      </p>
                    </v-col>

                    <v-col cols="1" class="text-right">
                      <router-link
                        to
                        class="text-decoration-none black--text fontcolor-black-light"
                      >
                        <div @click="dialog = false">X</div>
                      </router-link>
                    </v-col>
                  </v-row>
                </v-card-title>
                <v-card-text>
                  <div class="address-book-line my-1"></div>
                  <v-row
                    class="mt-12"
                    justify="center"
                    align="center"
                    v-if="addressInProgress"
                  >
                    <v-progress-circular
                      :size="60"
                      color="primary"
                      indeterminate
                    ></v-progress-circular>
                  </v-row>

                  <MeVerifyAddressComponent
                    v-else
                    :verifyAddress="addressFields"
                    :geoCodedAddress="geoCodedAddress"
                    :geoCodedAddressFlag="geoCodedAddressFlag"
                  />
                </v-card-text>
                <hr />
                <v-card-actions class="px-2 py-3">
                  <v-row no-gutters>
                    <v-col cols="12" class="text-right">
                      <v-hover v-slot:default="{ isHovering, props }">
                        <v-btn
                          class="text-uppercase px-3 mr-2 my-2 address-book-button"
                          v-bind="props"
                          :variant="isHovering ? 'outlined' : 'outlined'"
                          :class="
                            isHovering ? ' bg-white text-primary' : 'bg-primary'
                          "
                          rounded="0"
                          size="large"
                          @click="dialog = false"
                          >EDIT ADDRESS</v-btn
                        >
                      </v-hover>
                      <v-hover v-slot:default="{ isHovering, props }">
                        <v-btn
                          class="text-uppercase px-3 mr-2 my-2 address-book-save-button"
                          v-bind="props"
                          :variant="isHovering ? 'outlined' : 'outlined'"
                          :class="
                            isHovering ? ' bg-white text-primary' : 'bg-primary'
                          "
                          rounded="0"
                          size="large"
                          @click="saveAddress"
                          :disabled="inProgress"
                        >
                          <v-progress-circular
                            :size="20"
                            color="success"
                            indeterminate
                            v-if="inProgress"
                          ></v-progress-circular
                          >SAVE ADDRESS
                        </v-btn>
                      </v-hover>
                    </v-col>
                  </v-row>
                </v-card-actions>
              </v-card>
            </v-dialog>
          </v-form>
        </div>
      </v-col>
    </v-row>

    <ConfirmationDialog
      :confirmationDialog="confirmationDialog"
      :confirmationDetails="confirmation"
      @actionRemove="removeAddress"
    ></ConfirmationDialog>
    <SnackbarComponent :snackbar="snackbar"></SnackbarComponent>
  </v-container>
</template>
<script>
/*eslint-disable*/
import BillingAddressComponent from "@/components/retailer/address/BillingAddressComponent.vue";
import ShippingAddressComponent from "@/components/retailer/address/ShippingAddressComponent.vue";
import ShippingAddressFormComponent from "@/components/retailer/address/ShippingAddressFormComponent.vue";
import MeVerifyAddressComponent from "@/components/retailer/address/MeVerifyAddressComponent.vue";
// import ContactInfoComponent from "@/components/retailer/contact-info/ContactInfoComponent";
//import { doFormatAddress } from "@/services/util.service";
import { loginInterrupt } from "@/services/nav";
import SnackbarComponent from "@/components/common/SnackbarComponent.vue";
import ConfirmationDialog from "@/components/common/ConfirmationDialog.vue";
import VueTelInput from 'vue-tel-input';
//import BillingAddressComponent from "@/components/retailer/address/BillingAddressComponent.vue";

import { createHelpers } from "vuex-map-fields";

const { mapFields } = createHelpers({
  getterType: "accountOne/getField",
  mutationType: "accountOne/updateField",
});
export default {
  name: "AddressBook",
  data() {
    return {
      setCountryCode: "US",
      phoneNumberError: false,
      confirmationDialog: false,
      confirmation: {
        confirmationMessage: "",
      },
      dialog: false,
      deleteAddressDialog: false,
      addressObj: {},
      valid: true,
      lazy: false,
      geoCodedAddress: "",
      geoCodedAddressFlag: false,
      addressInProgress: false,
      snackbar: {
        show: false,
        message: null,
        color: null,
        timeout: 0,
      },
      textRules: [
        (v) => !!v || "This field is required",
        (v) =>
          (v && v.length >= 3) || "This field must be at least 3 characters",
      ],
      phoneNumberRules: [
        (v) => !!v || "This field is required",
        (v) =>
          (v && v.length >= 8) || "Phone Number must be at least 8 characters",
      ],
    };
  },
  components: {
    ShippingAddressFormComponent,
    MeVerifyAddressComponent,
    //ContactInfoComponent,
    SnackbarComponent,
    BillingAddressComponent,
    ShippingAddressComponent,
    ConfirmationDialog,
    VueTelInput,
    //BillingAddressComponent
  },
  computed: {
    hideAndShowFields: function () {
      let currentName = this.$route.name;
      if (currentName === "AddressBook") {
        return false;
      }
      return null;
    },
    basicInfo: function () {
      return this.$store.state.accountOne.one;
    },
    addressFields: function () {
      return this.$store.state.accountOne.address;
    },
    errorMessage: function () {
      return this.$store.state.accountOne.errorMessage;
    },
    ...mapFields([
      "one",
      "address",
      "address.firstname",
      "address.lastname",
      "address.telephone",
      "address.company",
      "address.defaultShipping",
      "address.defaultBilling",
      "allCountries",
      "countryAllStates",
      "inProgress",
      "addressIndex",
    ]),
    userAuth: function () {
      return this.$store.state.auth.userAuth;
    },
    addressId: function () {
      return this.$route.params.addressId;
    },
    shippingAddressDetails: function () {
      return this.$store.state.accountOne.shippingAddressDetails;
    },
    billingAddressDetails: function () {
      return this.$store.state.accountOne.billingAddressDetails;
    },
    addresses: function () {
      return this.$store.state.accountOne.addresses;
    },
    address: function () {
      return this.$store.state.accountOne.address;
    },
    fetchInProgress: function () {
      return this.$store.state.accountOne.fetchInProgress;
    },
  },
  methods: {
    resetForm() {
      if (
        this.$refs.contactForm &&
        this.$refs.addressForm.$refs.shippingAddressform
      ) {
        this.$refs.contactForm.resetValidation();
        this.$refs.addressForm.$refs.shippingAddressform.resetValidation();
      }
    },
    phoneNumberValidation() {},
    submit: async function () {
      try {
         let validate = await this.$refs.contactForm.validate()
         let validateShippingAddressform = await this.$refs.addressForm.$refs.shippingAddressform.validate()
      if (validate && validate.valid && validateShippingAddressform && validateShippingAddressform.valid) {
          this.addressInProgress = true;
          this.dialog = true;
          let response = await this.$store.dispatch(
            "accountOne/validateAddress",
            this.addressFields
          );
          if (typeof response == "string") {
            this.geoCodedAddress = response;
            this.geoCodedAddressFlag = false;
          } else if (typeof response == "object") {
            this.geoCodedAddress = "Address is geocoded.";
            this.geoCodedAddressFlag = true;
          }
        }
        this.addressInProgress = false;
      } catch (error) {
        this.snackbar = {
          message: error,
          color: "error",
          show: true,
          timeout: 3000,
        };
      }
    },
    saveAddress: function () {
      this.$store
        .dispatch("accountOne/updateAddress")
        .then(() => {
          this.snackbar = {
            message: "Address Updated Successfully",
            color: "success",
            show: true,
            timeout: 3000,
          };
          let page = localStorage.getItem("cr_meCurrentPage");
          setTimeout(() => {
            if (page == "addressBook")
              this.$router.push({
                name: "AddressBook",
              });
            else
              this.$router.push({
                name: "AccountDashboard",
              });
          }, 1000);
        })
        .catch((error) => {
          this.snackbar = {
            message: error,
            color: "error",
            show: true,
            timeout: 3000,
          };
          setTimeout(() => {
            this.$router.push({
              name: "AccountDashboard",
            });
          }, 1000);
        });
      this.dialog = false;
    },
    editAddress(address, index) {
      this.resetForm();
      let addressId = "new";
      if (index == null) {
        this.addressIndex = null;
        this.$store.dispatch("accountOne/setAddress", null);
      } else {
        this.addressIndex = index;
        addressId = address.id;

        this.$store.dispatch("accountOne/setAddress", this.addresses[index]);
      }
      localStorage.setItem("cr_meCurrentPage", "addressBook");
      this.$router.push({
        name: "EditAddressBook",
        params: { addressId: addressId },
      });
    },
    deleteAddress(address) {
      this.addressObj = address;
      (this.confirmationDialog = true),
        (this.confirmation = {
          confirmationMessage: "Are you sure you want to delete this address?",
        });
    },
    removeAddress(action) {
      if (action.submit) {
        this.$store.dispatch("accountOne/deleteAddress", this.addressObj);
      }
      (this.confirmationDialog = false),
        (this.confirmation = {
          confirmationMessage: "",
        });
      this.addressObj = "";
    },
    validateNumber(number, data) {
      if (data.possible && data.valid) this.phoneNumberError = false;
      else this.phoneNumberError = true;
    },
  },
  async created() {
    if (this.$route.params.addressId == "new") {
      this.resetForm();
    }
    if (!this.userAuth) {
      loginInterrupt(
        window.location.href,
        "There was an access violation caused by your request. You need to sign back in please."
      );
    } else {
      this.$store.dispatch("accountOne/basicInfo");
      if (this.addressId !== "new") {
        this.$store.dispatch("accountOne/basicInfo", this.addressId);
      } else {
        this.$store.dispatch("accountOne/setAddress", null);
      }
    }
  },
};
</script>
<style src="./address_book.scss" lang="scss" scoped/>