<template>
  <div
    class="tw-bg-white md:tw-rounded-[24px] md:tw-mt-[30px] md:tw-pt-[60px] md:tw-pb-[150px] md:tw-px-[30px]"
  >
    <div v-if="getPath == null">
      <p class="tw-text-[26px] tw-font-bold tw-mb-[20px] md:tw-text-[18px]">
        {{ $t("Forgot Password") }}
      </p>
      <p class="tw-body-3 tw-text-black tw-mb-[24px]">
        {{
          $t(
            "Dont worry! It happens. Please enter the address associated with your account."
          )
        }}
      </p>
      <div v-if="wrongMessageActive" class="warning--text text-size-14 ps-1 mb-3">
        {{ $t('The Email entered is incorrect') }}
      </div>
      <v-form v-model="resendValid">
        <v-text-field
          v-model="Email"
          background-color="neutrals darken-1"
          :label="this.$t('Email')"
          placeholder=""
          filled
          rounded
          dense
          single-line
          :rules="[rules.email, rules.require]"
        ></v-text-field>
      </v-form>
      <div class="md:tw-flex md:tw-justify-center md:tw-items-center">
        <button
          @click="sendForgotMail"
          :disabled="!resendValid"
          :class="[
            'tw-block tw-w-full tw-py-[10px] tw-rounded-[16px] tw-border tw-border-solid tw-body-3 tw-font-normal tw-transition-all tw-duration-200 tw-ease-in-out',
            resendValid
              ? 'tw-text-white tw-bg-primary-default tw-border-primary-default'
              : 'tw-text-base-disable tw-bg-neutral-100 tw-border-neutral-100',
          ]"
        >
          {{ $t("Reset Password")
          }}<span v-if="disableBtn">({{ this.countdown }})</span>
        </button>
      </div>
    </div>
    <div v-if="getPath != null && resetSuccess == false">
      <p class="title">{{ $t("Reset Password") }}</p>
      <v-form v-model="resetValid">
        <v-text-field
          v-model="userData.Password"
          background-color="neutrals darken-1"
          :label="this.$t('Password') + '*'"
          :type="showPass ? 'text' : 'password'"
          placeholder=""
          filled
          rounded
          dense
          single-line
          persistent-hint
          :rules="[rules.checkPassword, rules.require]"
          :hint="
            this.$t(
              'Passwords must be 8-20 characters with at least 1 number, 1 lower case letter and 1 upper case letter'
            )
          "
          :append-icon="showPass ? 'mdi-eye' : 'mdi-eye-off'"
          @click:append="showPass = !showPass"
        ></v-text-field>
        <v-text-field
          v-model="userConfirmPass"
          background-color="neutrals darken-1"
          :label="this.$t('Confirm Password') + '*'"
          :type="showConfirmPass ? 'text' : 'password'"
          placeholder=""
          filled
          rounded
          dense
          single-line
          :rules="[rules.checkPassword, rules.require, rules.confirmPass]"
          :append-icon="showConfirmPass ? 'mdi-eye' : 'mdi-eye-off'"
          @click:append="showConfirmPass = !showConfirmPass"
        ></v-text-field>
      </v-form>
      <div class="md:tw-flex md:tw-justify-center md:tw-items-center">
        <button
          @click="resetUserPass"
          :class="[
            'tw-block tw-w-full tw-py-[10px] tw-rounded-[16px] tw-border tw-border-solid tw-body-3 tw-font-normal tw-transition-all tw-duration-200 tw-ease-in-out tw-text-white tw-bg-primary-default tw-border-primary-default']"
        >
          {{ $t("Reset Password") }}
        </button>
      </div>
    </div>
    <div v-if="resetSuccess">
      <p class="title">{{ $t("Password Reset") }}</p>
      <p class="neutrals--text text--darken-5 text-size-14">
        {{ $t("Congrats! Your password has been successfully reset") }}
      </p>
      <nuxt-link :to="localePath('/')">
        <v-btn
          @click="redirectHome"
          width="100%"
          color="primary"
          class="border-radius-16 mt-4"
        >
          <span class="text-capitalize">{{ $t("Explore with ShowEasy") }}</span>
        </v-btn>
      </nuxt-link>
      <v-spacer class="d-flex justify-center mt-5">
        <span
          class="text-size-12 primary--text"
          v-html="$t('Go to ShowEasy in sec', { second: this.countdown })"
        ></span>
      </v-spacer>
    </div>
    <v-dialog v-model="dialog" :width="$vuetify.breakpoint.smAndUp ? 423 : 294"
        @click:outside="$router.push(localePath('/user/forgot'))">
        <v-card class="tw-p-[30px]" :height="$vuetify.breakpoint.smAndUp ? 289 : 290">
          <v-spacer class="d-flex align-center tw-justify-between tw-mb-[30px]">
            <div class="tw-text-[20px] tw-font-bold tw-text-black">
              {{ $t("Verify your email") }}
            </div>
            <v-btn @click="$router.push(localePath('/user/forgot'))" icon>
              <v-icon> mdi-close </v-icon>
            </v-btn>
          </v-spacer>
          <v-spacer class="tw-mb-[40px]">
            <div class="tw-text-[16px] tw-text-neutrals-800">
              {{ $t("Oops! Seems like you haven't verified your email,please click the button below to resend a verification email.")}}
            </div>
          </v-spacer>
          <button @click="resendVerifyEmail()" class="tw-bg-primary-1 hover:tw-bg-primary-light tw-text-white  tw-text-[18px] tw-rounded-[16px] tw-px-[77px] tw-py-[13px]">
            {{ $t("Resend verification email") }}
          </button>
          <!-- <v-btn @click="resendVerifyEmail" class="primary tw-text-[18px] tw-w-auto" rounded
            :disabled="countdown > 0">
            <span v-if="countdown > 0">
              {{ `(${this.countdown})` }}
            </span>
          </v-btn> -->
        </v-card>
    </v-dialog>
    <v-dialog v-model="deleteDialog" :width="$vuetify.breakpoint.smAndUp ? 423 : 294"
        @click:outside="$router.push(localePath('/user/forgot'))">
        <v-card class="tw-p-[30px]" :height="$vuetify.breakpoint.smAndUp ? 289 : 290">
          <v-spacer class="d-flex tw-justify-between align-center tw-mb-[30px]">
            <div class="tw-text-[20px] tw-text-black tw-font-bold">
              {{ $t("Reactivate your account") }}
            </div>
            <v-btn @click="$router.push(localePath('/user/forgot'))" icon>
              <v-icon> mdi-close </v-icon>
            </v-btn>
          </v-spacer>
          <v-spacer class="tw-mb-[40px]">
            <div class="tw-text-[16px] tw-text-neutrals-800 tw-font-bold">
              {{ $t("Welcome back!")}}
            </div>
            <div class="tw-text-[16px] tw-text-neutrals-800">
              {{ $t("Looks like your account has been deactivated.")}}
              <br />
            {{ $t("Would you like to reactivate this account?")}}
            </div>
          </v-spacer>
          <button class="tw-bg-primary-1 tw-text-white hover:tw-bg-primary-light tw-text-[18px] tw-rounded-[16px] tw-px-[86px] tw-py-[13px]">
            {{ $t("Reactivate my account") }}
          </button>
          <!-- <v-btn class="primary  tw-w-auto" rounded
            :disabled="countdown > 0">
            <span v-if="countdown > 0">
              {{ `(${this.countdown})` }}
            </span>
          </v-btn> -->
        </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: "Forgot",
  layout: "login",
  auth: false,
  data() {
    return {
      showPass: false,
      showConfirmPass: false,
      resendValid: false,
      resetValid: false,
      disableBtn: false,
      resetSuccess: false,
      countdown: 0,
      Email: "",
      userConfirmPass: "",
      userData: {
        //user_id: "",
        //auth_code: "",
        Password: "",
      },
      result: "",
      getPath: null,
      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"
          ),
        confirmPass: (v) =>
          v === this.userData.Password ||
          this.$t("Your password and confirmation password do not match"),
      },
      dialog: false,
      deleteDialog: false,
      wrongMessageActive: false,
    };
  },
  created(){
    this.$auth.$storage.removeUniversal('userPassword');
    this.$auth.$storage.removeUniversal('userAccount');
    this.getPAth();

  },
  methods: {
    getPAth(){
      let vm = this;
      if (this.$route.query.Email) {
        vm.getPath = vm.$route.query.Email;
      }else{
        vm.getPath = null;
      }
    },
    sendForgotMail() {
      this.$axios
        .post(`/trending/api/Signup/SendForgotMail?Email=${this.Email}`)
        .then((response) => {
          //console.log(JSON.stringify(response));
          if(response.data.STATUSCODE == "404"){
            this.resendValid = false;
            if(response.data.MSG == "0"){
              this.dialog = true;
            }else if(response.data.MSG == "2"){
              this.deleteDialog = true;
            }else{
              this.wrongMessageActive = true;
              
            }
          }
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data){
              this.result = data;
              this.disableBtn = !this.disableBtn;
              // this.timeout = setInterval(() => {
              //   if (this.countdown > 0) {
              //     this.countdown--;
              //   }
              //   if (this.countdown === 0) {
              //     this.disableBtn = !this.disableBtn;
              //     this.countdown = 60;
              //     clearInterval(this.timeout);
              //   }
              // }, 1000);
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    resetUserPass() {
      if (
        this.userData.Password === this.userConfirmPass &&
        this.resetValid
      ) {
        //this.userData.user_id = this.$route.query.user_uuid;
        //this.userData.auth_code = this.$route.query.auth_code;
        this.$axios
          .post(`/trending/api/Signup/ResetPassword?Email=${this.getPath}&Password=${this.userData.Password}`)
          .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.resetSuccess = !this.resetSuccess;
              this.countdown = 3;
              this.timer = setInterval(() => {
                if (this.countdown > 0) {
                  this.countdown--;
                } else {
                  clearInterval(this.timer);
                  this.$router.push(this.localePath("/"));
                }
              }, 1000);
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
      }
    },
    resendVerifyEmail() {
      this.countdown = 60;
      this.$axios
      .post(
            `/trending/api/Signup/ReSendVerifyMail?Email=${this.Email}`
          )
          .then((response) => {
            //console.log(JSON.stringify(response))
            if(response && response.data){

              clearInterval(this.timer);
            this.timer = setInterval(() => {
              if (this.countdown > 0) {
                this.countdown--;
              }
              if (this.countdown === 0) {
                clearInterval(this.timer);
              }
            }, 1000);
            }
        })
        .catch((error) => {
          console.log(error);
        });
          
    },
  },
  beforeUnmount() {
    clearInterval(this.timeout);
    clearInterval(this.timer);
  },
};
</script>

<style scoped>
.title {
  font-weight: 700;
  font-size: 26px;
  line-height: 34px;
  letter-spacing: 0.02em;
  color: #232323;
}
</style>
