<template>
  <div class="flex-row-container flex-all-center full-height">
    <form @submit.prevent="signinWithCode">
      <div class="form-input-back" @click="frontPage">
        <svg-icon icon="back" class-name="input-back-icon" />
        <p>{{email}}</p>
      </div>
      <div class="input-container">
        <div class="form-group">
          <div class="input-group-container">
            <div class="form-floating">
              <input
                class="input-email"
                id="inputCode"
                type="text"
                :placeholder="'Code sent to your email'"
                v-model="code"
                @focus="inputFocus"
              />
              <label for="inputCode">{{ $t('Authenticaion Code Sent To Your Email') }}</label>
            </div>
            <button type="submit" class="btn-start">{{ $t('SIGN IN') }}</button>
          </div>
        </div>
        <p class="error-msg" v-if="message != null">{{ message }}</p>
        <p class="error-msg" v-if="!message">
          <span>{{$t('Didn\'t get the email? Check junk folder or')}}</span>
          <button class="btn btn-link resend-btn" :disabled="countdown !== 0" type="button" @click="trySigninWithEmail">send again</button>
          <span v-if="countdown !== 0" class="countdown">({{countdown}})</span>
        </p>
      </div>
    </form>
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon.vue'
import { signinActionEnum } from '@/types'
import { UserAuthApi } from '@/utils/index'
export default {
  name: 'SigninWithEmailAndCode',
  components: { SvgIcon },
  props: {
    email: {
      required: true,
      type: String
    }
  },

  data() {
    return {
      code: null,
      message: null,
      preferred_region: null,
      countdown: 0,
      timer: null
    }
  },

  created() {},
  mounted() {
    if (this.mnx_IsKeepUserSignedIn() && this.mnx_isUserAuthenticated()) {
      this.mnx_navAfterSignedin()
    }
    this.startCountdown()
  },
  unmounted() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    frontPage() {
      window.history.go(-1)
    },
    inputFocus() {
      this.message = null
    },
    startCountdown() {
      this.countdown = 60
      this.timer = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(this.timer)
          this.timer = null
          return
        }
        this.countdown = this.countdown - 1
      }, 1000)
    },
    trySigninWithEmail() {
      UserAuthApi.trySigninWithEmail(this.email, window.location.host)
        .then(() => {
          this.startCountdown()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    signinWithCode() {
      this.message = null
      if (this.code === null || this.code.length < 1) {
        this.message = this.$t('Please type in the code sent to your email')
        return
      }

      // this.message = userProfileValidator.authCodeValidator.validate(this.code);

      if (this.message != null) return

      UserAuthApi.signinWithEmailAndCode(this.email, this.code, window.location.host)
        .then((response) => {
          let signinAction = response.data.signin_result
          this.preferred_region = response.data.preferred_region
          switch (signinAction) {
            case signinActionEnum.VERIFY_EMAIL_WITH_AUTH_CODE:
              this.message = this.$t('Invalid auth code')
              break
            case signinActionEnum.EXISTING_USER_PASSWORD_REQUIRED:
              this.mnx_navToSignWithEmailAndPassword(this.email)
              break
            case signinActionEnum.NEW_USER_SET_PASSWORD:
            case signinActionEnum.REVIEW_AND_REVISE_FLID:
            case signinActionEnum.USER_SIGNED_IN:
              this.mnx_userSignedin(response.data, this.keepSignedin)
              break
            default:
              console.log(signinAction)
          }
        })
        .catch((error) => {
          if (error.response && error.response.status == 401) {
            this.message = this.$t('invalid code')
          } else {
            console.log(error)
          }
        })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.resend-btn {
  font-weight: 500;
  padding: 0;
  font-size: 18px;
  &:disabled {
    color: $primary;
    opacity: .78;
  }
}
.countdown {
  color: $primary;
}
</style>
