<template>
  <div class="setting xl:tw-max-w-[1246px] xl:tw-mx-auto">
    <div class="xl:tw-flex xl:tw-justify-between xl:tw-items-start">
      <userSidebar :userData="userData" :firstName="firstName" :lastName="lastName" class="tw-hidden xl:tw-block">
      </userSidebar>
      <div class="tw-bg-white xl:tw-p-[30px] xl:tw-rounded-[20px] xl:tw-min-w-[900px] xl:tw-max-w-[900px]">
        <div class="tw-text-[20px] tw-font-bold tw-text-base-primary tw-mb-[20px] md:t24 md:tw-mb-[30px]">
          <two-dots class="tw-mr-[30px]"></two-dots>{{ $t("userProfile.setting") }}
        </div>
        <div class="tw-mb-[30px] md:tw-max-w-[392px]">
          <div class="tw-body-2 tw-font-bold tw-text-base-primary tw-mb-[15px] md:t16">
            {{ $t('userProfile.account') }}
          </div>
          <input type="text"
            class="tw-h-[40px] tw-w-full tw-border tw-bg-white tw-border-neutral-200 tw-border-solid tw-px-[20px] tw-py-[10px] tw-rounded-[5px] disabled:tw-text-base-disable"
            :value="userData.Account" disabled />
        </div>
        <Transition name="bounce">
          <div>
            <div class="tw-body-2 tw-font-bold tw-text-base-primary tw-mb-[20px] md:t16 md:tw-mb-[15px]">
              {{$t('userProfile.resetPassword')}}
            </div>
            <div class="tw-mb-[20px] md:tw-max-w-[392px] md:tw-mb-[15px]">
              <div class="tw-mb-[20px] md:tw-max-w-[392px] md:tw-mb-0">
              <div class="tw-text-[16px] tw-text-base-primary tw-mb-[6px] md:tw-text-[14px]">
                {{$t('userProfile.oldPassword')}}
              </div>
              <v-text-field type="password" v-model="userPass.user_old_pass" @blur="checkOldPassword($event)" :rules="[rules.checkPassword, rules.require]"
                hide-details dense outlined validate-on-blur></v-text-field>
            </div>
              <div v-show="!isOldPassValid" class="tw-footer-body tw-w-full tw-leading-none tw-pt-1" :class="
                isOldPassValid
                  ? 'tw-text-neutrals-400'
                  : 'tw-text-error-default'
              ">
                {{ $t('userProfile.passwordsHint') }}
              </div>
            </div>
            <div class="tw-mb-[20px] md:tw-max-w-[392px] md:tw-mb-[15px]">
              <div>
                <div class="tw-text-[16px] tw-text-base-primary tw-mb-[6px] md:tw-text-[14px]">
                  {{$t('userProfile.newPassword')}}
                </div>
                <v-text-field v-model="userPass.user_new_pass" :append-icon="showPass ? 'mdi-eye' : 'mdi-eye-off'"
                  @click:append="showPass = !showPass" @blur="checkPassword($event)"
                  :type="showPass ? 'text' : 'password'" :rules="[rules.checkPassword, rules.require]" hide-details
                  dense outlined validate-on-blur></v-text-field>
              </div>
              <div v-show="!isNewPassValid" class="tw-footer-body tw-w-full tw-leading-none tw-pt-1" :class="
                isNewPassValid
                  ? 'tw-text-neutrals-400'
                  : 'tw-text-error-default'
              ">
                {{ $t('userProfile.passwordsHint') }}
              </div>
            </div>
            <div class="tw-mb-[20px] md:tw-max-w-[392px] md:tw-mb-[15px]">
              <div>
                <div class="tw-text-[16px] tw-text-base-primary tw-mb-[6px] md:tw-text-[14px]">
                  {{$t('userProfile.confirmPassword')}}
                </div>
                <v-text-field v-model="confirmPass" :append-icon="showConfirmPass ? 'mdi-eye' : 'mdi-eye-off'"
                  @click:append="showConfirmPass = !showConfirmPass" :type="showConfirmPass ? 'text' : 'password'"
                  :rules="[rules.checkConfirmPassword, rules.require]" dense outlined validate-on-blur></v-text-field>
              </div>
            </div>
          </div>
        </Transition>
        <Transition name="bounce">
          <div 
            :lass="['tw-mb-[64px] md:tw-flex md:tw-flex-row md:tw-items-center md:tw-mb-[40px]']">
            <button @click="resetPassword"
              class="tw-text-white tw-bg-primary-1 tw-text-[18px] tw-rounded-[16px] tw-w-full tw-py-[13px] tw-mb-[15px] md:tw-text-[16px] md:tw-w-fit md:tw-px-[16px] md:tw-py-[10px] md:tw-mr-[20px] md:tw-mb-0">
              {{$t('userProfile.resetPassword')}}
            </button>
            <button @click="cancel"
              class="tw-text-primary-1 tw-bg-white tw-text-[18px] tw-rounded-[16px] tw-w-full tw-py-[13px] md:tw-text-[16px] md:tw-w-fit md:tw-px-[16px] md:tw-py-[10px]">
              {{$t('userProfile.cancel')}}
            </button>
          </div>
        </Transition>
        <button @click="openDeleteModal()"
          class="tw-text-error-default tw-text-[16px] tw-underline tw-mt-[44px] md:tw-mt-[99px] xl:tw-mt-[39px]">
          {{$t('userProfile.deleteAccount')}}
        </button>
      </div>
    </div>
    <Transition name="bounce">
      <unLinkModal></unLinkModal>
    </Transition>
    <Transition name="bounce">
      <deleteAccountModal :userData="userData"></deleteAccountModal>
    </Transition>
  </div>
</template>
<script>
import Setting from "../../components/user/Setting.vue";
import SettingDialog from "../../components/user/settingDialog.vue";
import BookingList from "../../components/user/bookingList.vue";
import TwoDots from "@/components/TwoDots";
import userSidebar from "@/components/user/userSidebar.vue";
import unLinkModal from "@/components/newComponent/modal/unLinkModal.vue";
import deleteAccountModal from "@/components/newComponent/modal/deleteAccountModal.vue";

export default {
  name: "setting",
  layout: "profile",
  components: {
    Setting,
    SettingDialog,
    BookingList,
    TwoDots,
    userSidebar,
    unLinkModal,
    deleteAccountModal,
  },
  data() {
    return {
      google: {},
      facebook: {},
      deleteDialogActive: false,
      valid: false,
      showPass: false,
      showConfirmPass: false,
      userPass: {
        user_old_pass: "",
        user_new_pass: "",
      },
      isNewPassValid: true,
      isOldPassValid: true,
      firstName: "",
      lastName: "",
      userData: {},
      SSOShow: 0,
      confirmPass: "",
      deleteAccountImg: require("~/assets/img/deleteAccount.png"),
      rules: {
        require: (value) => !!value || this.$t("Required."),
        email: (v) =>
          /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/.test(
            v
          ) || this.$t("Invalid email"),
        checkPassword: (v) =>
          (/(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])/.test(v) &&
            v.length >= 8 &&
            v.length <= 20) ||
          this.$t(
            "Passwords must be 8-20 characters with at least 1 number, 1 lower case letter and 1 upper case letter"
          ),
        checkConfirmPassword: (v) =>
          this.confirmPass === this.userPass.user_new_pass ||
          this.$t("Your password and confirmation password do not match"),
      },
    };
  },
  created() {
    this.fetchUserData();
    if (process.browser) {
      window.addEventListener("resize", this.handleResize);
    }
  },
  mounted() {
    this.$nextTick(() => {
      window.addEventListener("resize", this.onResize);
    });
  },
  destroyed() {
    if (process.browser) {
      window.removeEventListener("resize", this.handleResize);
    }
  },
  computed: {
    windowWidth() {
      if (process.client) {
        this.width = window.innerWidth;
      }
      return this.width;
    },
  },
  methods: {
    handleResize() {
      if (process.browser) {
        this.width = window.innerWidth;
      }
    },
    //Get Member Info
    fetchUserData() {
      this.$axios
        .get(
          `/trending/api/Members/Info`
        )
        .then((response) => {
          //console.log(JSON.stringify(response));
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data){
              this.userData = data;
              this.firstName = this.userData.FirstName;
              this.lastName = this.userData.LastName;
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    resetPassword() {
      if (
        this.isNewPassValid && this.isOldPassValid &&
        this.userPass.user_new_pass !== this.userPass.user_old_pass &&
        this.userPass.user_new_pass == this.confirmPass
      ) {
        this.$axios
      .post(
          `/trending/api/Members/ResetNewPassword/?Password=${this.userPass.user_new_pass}`
        )
        .then((response) => {
          //(JSON.stringify(response));
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data){
              this.$auth.$storage.removeUniversal("userPicture");
              this.$auth.$storage.removeUniversal("userLastName");
              this.$auth.$storage.removeUniversal("userAccount");
              this.$auth.$storage.removeUniversal("userPassword");
            this.$notify({
              type: "success",
              title: "Awesome!",
              text: "Your password has been updated successfully.",
            });
            setTimeout(() => {
              this.$auth.logout();
              this.$router.push(this.localePath("/user"));
            }, 4000)
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
      }
    },
    cancel(){
      this.userPass.user_old_pass = "",
      this.userPass.user_new_pass = "",
      this.confirmPass = ""
    },
    checkOldPassword(v) {
      const pass = v.target.value;
      this.isOldPassValid =
        /(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])/.test(pass) &&
        pass.length >= 8 &&
        pass.length <= 20;
    },
    checkPassword(v) {
      const pass = v.target.value;
      this.isNewPassValid =
        /(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])/.test(pass) &&
        pass.length >= 8 &&
        pass.length <= 20;
    },
    openDeleteModal() {
      this.$modal.show('deleteAccountModal');
    }
  },
};
</script>

<style scoped lang="scss">
:deep(.v-text-field.v-text-field--enclosed .v-text-field__details) {
  padding: 0;
  margin: 0;
}

:deep(.v-messages__message) {
  font-size: 14px;
}

.v-text-field--outlined::v-deep {
  fieldset {
    border-color: #e5e5e5;
  }
}

.bounce-enter-active {
  animation: bounce-in 0.3s ease-out;
}

.bounce-leave-active {
  animation: bounce-in 0.3s cubic-bezier(1, 0.5, 0.8, 1) reverse;
}

@keyframes bounce-in {
  0% {
    opacity: 0;
    transform: translateY(-10px);
  }

  50% {
    opacity: 0.5;
    transform: translateY(-5px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
