<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="xl:tw-hidden"></div> -->
      <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 v-show="SSOShow == 2" :class="['tw-mb-[50px] md:tw-mb-[30px]',SSOShow == 2 ? '':'tw-hidden']">
            <div class="tw-body-2 tw-font-medium tw-text-base-primary tw-mb-[15px] md:t16">
              {{ $t('userProfile.manageSSO')}}
            </div>
            <div class="md:tw-flex md:tw-flex-row">
              <div
                class="tw-w-full tw-border tw-border-solid tw-border-neutral-200 tw-rounded-[10px] tw-grid tw-grid-cols-[auto_71px] tw-items-center tw-gap-[50px] tw-px-[30px] tw-py-[14px] tw-mb-[20px] md:tw-mb-0 md:tw-mr-[20px] md:tw-py-[30px]">
                <div class="tw-text-[16px] tw-text-base-primary md:tw-text-[14px]">
                  Facebook
                </div>
                <button v-if="facebook.social_schema" @click="openModal('facebook')"
                  class="tw-bg-warning-background tw-text-warning-default tw-rounded-[12px] tw-px-[16px] tw-py-[9px] tw-whitespace-nowrap">
                  {{$t('userProfile.SSOUnLink')}}
                </button>
                <button v-else @click="facebookLogin"
                  class="tw-bg-warning-default tw-text-white tw-rounded-[12px] tw-px-[16px] tw-py-[9px]">
                  {{$t('userProfile.SSOLink')}}
                </button>
              </div>
              <div
                class="tw-w-full tw-border tw-border-solid tw-border-neutral-200 tw-rounded-[10px] tw-grid tw-grid-cols-[auto_90px] tw-items-center tw-gap-[50px] tw-px-[30px] tw-py-[14px] md:tw-py-[30px]">
                <div class="tw-text-[16px] tw-text-base-primary md:tw-text-[14px]">
                  Google
                </div>
                <button v-if="google.social_schema" @click.prevent="openModal('google')"
                  class="tw-bg-warning-background tw-text-warning-default tw-rounded-[12px] tw-px-[16px] tw-py-[9px]">
                  {{$t('userProfile.SSOUnLink')}}
                </button>
                <button v-else @click="googleLogin"
                  class="tw-bg-warning-default tw-text-white tw-rounded-[12px] tw-px-[16px] tw-py-[9px]">
                  {{$t('userProfile.SSOLink')}}
                </button>
              </div>
            </div>
          </div>
        </Transition>
        <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>


              <!-- <input v-model="userPass.user_old_pass" type="password"
                class="tw-h-[40px] tw-w-full tw-border tw-border-neutral-200 tw-border-solid tw-px-[20px] tw-py-[10px] tw-rounded-[5px]" /> -->
            </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
              class="tw-text-[16px] tw-text-base-primary tw-mb-[6px] md:tw-text-[14px]"
            >
              New password
            </div>
            <input
              type="text"
              class="tw-h-[40px] tw-w-full tw-border tw-border-neutral-200 tw-border-solid tw-px-[20px] tw-py-[10px] tw-rounded-[5px] tw-mb-[6px]"
            />  -->
              <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
              class="tw-text-[16px] tw-text-base-primary tw-mb-[6px] md:tw-text-[14px]"
            >
              Confirm password
            </div>
            <input
              type="text"
              class="tw-h-[40px] tw-w-full tw-border tw-border-neutral-200 tw-border-solid tw-px-[20px] tw-py-[10px] tw-rounded-[5px] tw-mb-[6px]"
            />
            <img
              src="~/assets/svg/hidepassword.svg"
              class="tw-absolute tw-top-[717px] tw-right-[20px] md:tw-top-[621px] md:tw-left-[359px] xl:tw-left-[777px] xl:tw-top-[650px]"
              alt=""
            /> -->
            </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 SavedExhibitions from "../../components/user/savedExhibitions.vue";
import SavedExhibitionsDialog from "../../components/user/savedExhibitionsDialog.vue";
import Setting from "../../components/user/Setting.vue";
import SettingDialog from "../../components/user/settingDialog.vue";
import CropImageDialog from "../../components/user/cropImageDialog.vue";
import CompanyInfo from "../../components/user/companyInfo.vue";
import CompanyInfoDialog from "../../components/user/companyInfoDialog.vue";
import ContactInfo from "../../components/user/contactInfo.vue";
import vClickOutside from "v-click-outside";
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",
  directives: {
    clickOutside: vClickOutside.directive,
  },
  components: {
    SavedExhibitions,
    SavedExhibitionsDialog,
    Setting,
    SettingDialog,
    CropImageDialog,
    CompanyInfo,
    CompanyInfoDialog,
    ContactInfo,
    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.geiApiDemo();
    this.fetchUserData();
    if (process.browser) {
      window.addEventListener("resize", this.handleResize);
    }
    //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;
      }
    },
    // geiApiDemo(){
    //   this.$axios
    //     .get(
    //       `/trending/api/Members/Info`
    //     )
    //     .then((res) => {
    //       console.log(JSON.stringify(res));
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },
    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;
              //console.log("userData:" + this.userData);
              this.firstName = this.userData.FirstName;
              this.lastName = this.userData.LastName;
              // this.facebook =
              //   res.data.UserSocialRelation.filter(
              //     (item) => item.social_schema === "facebook"
              //   )[0] || {};
              // this.google =
              //   res.data.UserSocialRelation.filter(
              //     (item) => item.social_schema === "google"
              //   )[0] || {};
              // this.checkSSO();
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    removeSocialRelation(schema) {
      delete schema.social_id;
      this.$axios
        .put(
          `/member/users/social?jwt=${this.$auth.$storage.getUniversal("jwt").token || ""
          }`,
          schema
        )
        .then((result) => {
          this.$emit("refetch-user");
        })
        .catch((err) => {
          console.log(err);
        });
      this.$nextTick(() => {
        schema.social_schema === "google"
          ? (this.google = {})
          : (this.facebook = {});
      });
    },
    facebookLogin() {
      this.$auth.loginWith("facebook");
    },
    googleLogin() {
      this.$auth.loginWith("google");
    },
    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;
    },
    checkSSO() {
      if (Object.keys(this.facebook).length == 0 && Object.keys(this.google).length == 0) {
        this.SSOShow = 1;
      } else {
        this.SSOShow = 2;
      }
    },
    openModal(type) {
      if (type == 'google') {
        if (Object.keys(this.facebook).length == 0) {
          this.$modal.show('unLinkModal');
        } else {
          this.removeSocialRelation(this.google);
        }
      }

      if (type == 'facebook') {
        if (Object.keys(this.google).length == 0) {
          this.$modal.show('unLinkModal');
        } else {
          this.removeSocialRelation(this.facebook);
        }
      }
    },
    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>