<template>
  <div class="sign-up">
    <div class="sign-up__text-number">
      <div v-if="getFullName?.name?.length && getFullName?.last_name?.length">
        "{{ userFullname(getFullName) }}" عزیز، خوش آمدید.
      </div>

      <div v-else>0{{ getMobile }}</div>
    </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"
          :class="{ 'form-group--error': $v.code.$error }"
        >
          <input
            class="form-control"
            type="text"
            name="code"
            id="code"
            placeholder="xxxxx"
            v-model.trim="$v.code.$model"
            @input="resetErrors"
            dir="ltr"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!$v.code.required">
            {{ $t("IsRequired") }}
          </div>
          <div class="error" v-if="!$v.code.minLength">
            {{ $t("CodeIsNotCorrect") }}
          </div>
        </div>
      </div>
      <!-- <div class="form-group" :key="rerenderer"> -->
      <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>

      <!-- hide if user already entered its firstname and lastname -->
      <div v-if="!getFullName?.name?.length || !getFullName?.last_name?.length">
        <div class="sign-up__form-row sign-up__simple-input">
          <div
            class="form-group position-relative"
            :class="{ 'form-group--error': $v.name.$error }"
          >
            <input
              class="form-control elem__placeholder-gray"
              v-model.trim="$v.name.$model"
              type="text"
              placeholder="نام"
              name="name"
              id="name"
              autocomplete="off"
            />
          </div>
          <div v-if="submitStatus === 'ERROR'">
            <div class="error" v-if="!$v.name.required">
              {{ $t("IsRequired") }}
            </div>
          </div>
        </div>
        <div class="sign-up__form-row sign-up__simple-input">
          <div
            class="form-group position-relative"
            :class="{ 'form-group--error': $v.last_name.$error }"
          >
            <input
              class="form-control elem__placeholder-gray"
              v-model.trim="$v.last_name.$model"
              type="text"
              placeholder="نام خانوادگی"
              name="last_name"
              id="last_name"
              autocomplete="off"
            />
          </div>
          <div v-if="submitStatus === 'ERROR'">
            <div class="error" v-if="!$v.last_name.required">
              {{ $t("IsRequired") }}
            </div>
          </div>
        </div>
      </div>
      <div class="sign-up__button-container">
        <a @click.prevent="goBack" :href="$t('Back')">{{ $t("Back") }}</a>
        <button :disabled="loading" v-on:click="doActivate">
          {{ $t("Verify") }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import authMixin from "~/mixins/authMixin";
import { required,minLength } from '@vuelidate/validators'
import useVuelidate from '@vuelidate/core'


import { mapState } from "pinia";

export default {
  validations: {
    code: {
      required,
    },
    name: {
      required,
    },
    last_name: {
      required,
    },
  },

  mixins: [authMixin],
  beforeMount() {
    this.name = this.getFullName?.first_name;
    this.last_name = this.getFullName?.last_name;
  },
  mounted() {
    this.countDownTimer();
  },
  beforeDestroy() {
    clearInterval(this.downloadTimer);
  },

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

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

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

        this.getActivationCode({
          mobile: parseInt(vm.getMobile, 10),
          code: vm.code,
          name: vm.name,
          last_name: vm.last_name,
        })
          .then((res) => {
            this.submitStatus = "OK";

            // if (this.enableResetPassword)
            //   this.$router.push({
            //     name: "resetpass",
            //     params: { usernameemail: vm.usernameemail },
            //   });
            // else {

            vm.mySwalToast({
              title: res.message,
              icon: "success",
            });

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

    getcode() {
      var vm = this;
      vm.enableResendCode = false;

      this.phoneLogin({
        mobile: parseInt(vm.mobile, 10),
      }).then((res) => {
        mySwalToast({
          title: res.message,
          icon: "success",
        });
        this.rerenderer++;
        this.countDownTimer();
      });
    },
    countDownTimer(timeInSecond = 120) {
      const vm = this;

      var timeleft = timeInSecond;
      var downloadTimer = setInterval(function () {
        if (timeleft <= 0) {
          if (vm.$refs?.countdown) vm.$refs.countdown.innerHTML = "ارسال مجدد";
          vm.enableResendCode = true;
          clearInterval(downloadTimer);
        } else {
          if (vm.$refs?.countdown) 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>
