<template>
  <div class="m-sign-up">
    <div class="m-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="m-sign-up__text">رمز پیامک شده را وارد کنید</div>
    <div class="m-sign-up__form">
      <div class="m-sign-up__form-row m-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="m-sign-up__form-row m-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="m-sign-up__form-row m-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="m-sign-up__button-container">
        <a @click.prevent="goBack" :href="$t('Back')">{{ $t("Back") }}</a>
        <button  v-on:click="doActivate">
          {{ $t("Verify") }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import authMixin from "~/mixins/authMixin";
import { required, minLength } from "vuelidate/lib/validators";
import { useCommonStore } from "~/stores/commonStore";
import { useAuthStore } from "~/stores/authStore";
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",
            }); 

            const { $eventBus } = useNuxtApp();
            $eventBus.emit(
                'authenticated-by-modal',
                this.$route.query["invite-id"]
              );
              
            // 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 = 10) {
      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: 1.2rem !important;
  color: #00b6e3 !important;
  margin: 0 !important;
  display: inline-block !important;
  text-align: center !important;
  border: none !important;
  background:unset !important;
  &[disabled] {
    min-width: 4em !important;
  }
}
</style>