
<script lang="ts" setup>
const auth = useAuthStore()
const { setToken, loadToken, getToken } = useAuthToken()
const { apiFetch } = useApi()

const loginCode = ref()
const loginCodePrefix = ref()
const codeExpire = ref()
const account = ref()
const isLoading = ref(false)
const charcode = ref()
const errorMessage = ref()
const successMessage = ref()
const router = useRouter()

async function sendCode() {
  isLoading.value = true
  errorMessage.value = false
  successMessage.value = false
  const { data } = await apiFetch('/tokenRequest', {
    method: "post",
    body: {
      account: account.value,
      code: loginCode.value,
      code_prefix: loginCodePrefix.value
    }
  })

  if (data.value?.error) {
    errorMessage.value = data.value?.message
  }

  if (data.value?.success) {
    if (data.value?.message) {
      successMessage.value = data.value?.message
    }
    if (data.value?.token) {
      await setToken(data.value.token)
      window.localStorage.removeItem('codePrefix')
      window.localStorage.removeItem('codeExpire')
      if (data.value?.user) {
        auth.user = data.value.user
      }
      return navigateTo('/')
    }
  }

  isLoading.value = false
}


function codeExpired() {
  console.log('Code expired!')
    loginCodePrefix.value = null
    codeExpire.value = null
    router.push({path:'/login'})
}

function changeCode() {
    if (loginCode.value.length === 4) {
        sendCode()
    }
}

onMounted(async () => {
  // Ha már be van jelentkezve, irányítsuk a főoldalra
  await loadToken()
  const token = getToken()
  if (token) {
    return navigateTo('/')
  }

  loginCodePrefix.value = window.localStorage.getItem('codePrefix')
  codeExpire.value = window.localStorage.getItem('codeExpire')
  account.value = window.localStorage.getItem('account')
  window.document.addEventListener('keydown', function(e){
    console.log(e)
    charcode.value = e.key
    if(e.key === 'Backspace' && loginCode.value.length > 0){
      loginCode.value = loginCode.value.substr(0,loginCode.value.length-1)
    }
  })
})
</script>

<template>
  <div>
    <Message class="w-full" severity="error" v-if="errorMessage">{{ errorMessage }}</Message>
    <Message class="w-full" severity="success" v-if="successMessage">{{ successMessage }}</Message>
    <div class="p-2">
      Add meg a kódot amit a(z) <b>{{ account }}</b> e-mail címre küldött ki rendszerünk.
    </div>
    <Card>
      <template #content>
        <div class="flex flex-wrap justify-center gap-1 items-center p-2 relative">
          <CardLoading v-if="isLoading" />
          <InputOtp v-model="loginCodePrefix" :length="2" style="gap: 1; opacity:1" in disabled size="small">
          </InputOtp>
          <div><i class="pi pi-minus"></i></div>
          <InputOtp v-model="loginCode" :length="4" style="gap: 1" size="small" @change="changeCode($event)" integer-only></InputOtp>
        </div>
      </template>
    </Card>
    <div class="p-2">
      A kód még <b>
        <Countdown v-if="codeExpire" :expired="codeExpire" @end="codeExpired()" />
      </b> percig érvényes. Lejárat után új kódot kell igényelned.
    </div>
    <Alert>
      {{ errorMessage }}
    </Alert>
    <Button @click="sendCode()" class="w-full" icon="pi pi-check-circles">Kód küldése</Button>

    <Button @click="$router.push({path:'/login'})" variant="link" class="w-full mt-3" icon="pi pi-check-circles">Új kód kérése</Button>
  </div>
</template>


<style>
.p-disabled, .p-component:disabled
{
  opacity: 0.9;
}</style>