<template>
  <div class="sign-up">
    <div class="sign-up__text-number">
      {{ getFullName && getFullName.length ? getFullName : getMobile }}
    </div>
    <div class="sign-up__text">رمز پیامک شده را وارد کنید</div>
    <div class="sign-up__form">
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': $v.code.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            v-model.trim="$v.code.$model"
            type="text"
            placeholder="کد ارسالی"
            name=""
            id=""
            dir="ltr"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!$v.code.required">
            {{ $t("IsRequired") }}
          </div>
        </div>
        <div class="form-group">
          کد تایید را دریافت نکرده اید؟

          <button
            :disabled="!enableResendCode"
            @click.prevent="getcode"
            title="ارسال مجدد"
            class="resend-code-btn"
            type="button"
          >
            <span ref="countdown" id="countdown"></span>
          </button>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': $v.password.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            type="password"
            name=""
            id=""
            v-model.trim="$v.password.$model"
            placeholder="رمز عبور"
            dir="ltr"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!$v.password.required">
            {{ $t("IsRequired") }}
          </div>
          <div class="error" v-if="!$v.password.minLength">
            Password must have at least
            {{ $v.password.$params.minLength.min }} letters.
          </div>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': $v.repassword.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            type="password"
            name=""
            id=""
            v-model.trim="$v.repassword.$model"
            placeholder="تکرار رمز عبور"
            dir="ltr"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!$v.repassword.required">
            {{ $t("IsRequired") }}
          </div>
          <div class="error" v-if="!$v.repassword.sameAsPassword">
            رمزهای عبور باید یکسان باشند.
          </div>
        </div>
      </div>

      <div class="sign-up__button-container">
        <RouterLink :to="{ path: '/login' }">بازگشت</RouterLink>

        <button v-on:click="doActivate">ثبت کد</button>
      </div>
    </div>
  </div>
</template>

<script>
import authMixin from "~/mixins/authMixin";
import {
  required,
  minLength,
  sameAs,
} from "@vuelidate/validators";
import { mapState, mapActions } from "pinia";

export default {
  validations: {
    password: {
      required,
      minLength: minLength(6),
    },
    repassword: {
      required,
      sameAsPassword: sameAs("password"),
    },
    code: {
      required,
    },
  },
  // props: ["usernameemail"],
  mixins: [authMixin],
  mounted() {
    this.countDownTimer();
    this.getcode();
  },
  beforeDestroy() {
    clearInterval(this.downloadTimer);
  },

  data() {
    return {
      code: "",
      password: "",
      repassword: "",
      downloadTimer: undefined,
      enableResendCode:false
    };
  },
  computed: {
    ...mapState(useAuthStore,["getResetPasswordState", "getFullName", "getMobile"]),
  },
  methods: {
    resetErrors() {
      if (this.$v.$invalid) this.$v.$reset();
    },

    doActivate() {
      this.$v.$touch();
      const vm = this;

      if (this.$v.$invalid) {
        this.submitStatus = "ERROR";
      } else {
        if (this.loading) return false;
        this.loading = true;

        this.resetPassword({
          username: this.getMobile,
          activationcode: this.code,
          newpass: this.password,
        })
          .then((res) => {
            mySwalToast({
              title: res.message,
              icon: "success",
            });

            this.submitStatus = "OK";
            this.$router.push({
              name: "login",
            });
          })
          .catch((err) => {
            mySwalToast({
              title: err.message,
              icon: "error",
            });
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    getcode() {
      const vm = this;

      this.$v.$touch();
      vm.enableResendCode = false;

      if (this.$v.$invalid) {
        this.submitStatus = "ERROR";
      } else {
        if (this.loading) return;
        this.loading = true;

        this.submitStatus = "PENDING";

        this.phoneLogin({
          mobile: this.getMobile,
        })
          .then(() => {
            this.submitStatus = "OK";
          })
          
          .finally(() => {
            this.loading = false;
          });
      }
    },
    countDownTimer(timeInSecond = 120) {
      const vm = this;

      var timeleft = timeInSecond;
      var downloadTimer = setInterval(function() {
        if (timeleft <= 0) {
          clearInterval(downloadTimer);
          vm.$refs.countdown.innerHTML = "ارسال مجدد";
          vm.enableResendCode = true;
        } else {
          vm.$refs.countdown.innerHTML = timeleft;
        }
        timeleft -= 1;
      }, 1000);
    },
  },
};
</script>
<style lang="scss">
.resend-code-btn {
  height: 2.5em !important;
  min-width: auto !important;
  // font-size: 0.8rem!important;
  margin: 0 !important;
  display: inline-block !important;
  text-align: center !important;
  border: none !important;

  &[disabled] {
    min-width: 4em !important;
  }
}
</style>
