<template>
  <q-page class="flex column items-center justify-center">

    <q-card
      id="login_block"
      flat
      class="flex column items-center w80 justify-between q-py-lg login-card "
      >
      <login-logo
        class="col-grow q-pa-md"
        :style="{ alignItems: 'flex-end' }"
        />

      <div class="q-ma-md flex column input-login">
        <q-input
          v-model="login"
          autofocus
          dense
          filled
          class="q-mb-sm"
          :label="$t('login__email')"
          :rules="validationRules.email"
          lazy-rules="ondemand"
          no-error-icon
          @focus="emailInput?.resetValidation()"
          @blur="delayValidity('login')"
          ref="emailInput"
        />

        <q-input
          v-model="password"
          dense
          filled
          :label="$t('login__password')"
          class="q-mb-none q-mt-xs"
          :type="isPwd ? 'password' : 'text'"
          hide-hint
          :hint="passwordHint"
          :rules="validationRules.password"
          lazy-rules="ondemand"
          no-error-icon
          @focus="passwordInput?.resetValidation()"
          @blur="delayValidity('password')"
          ref="passwordInput"
          >
          <template #append>
            <q-icon
              color="grey-5"
              :name="isPwd ? 'mdi-eye-off-outline' : 'mdi-eye-outline'"
              class="cursor-pointer"
              @click="isPwd = !isPwd"
            />
          </template>

        </q-input>

        <div class="self-end">
          <q-btn
            @click.prevent="forgotPwd"
            flat
            no-caps
            dense
            class="text-grey"
            >
            {{$t('login__forgot_password')}}
          </q-btn>
        </div>
      </div>
      <q-btn
        @click="sendAuth()"
        color="primary"
        :disabled="!acceptTermsOfUse || !isEmailValid || !isPasswordValid"
        >
        {{$t('login__sign_in')}}
      </q-btn>
      <div class="q-pt-lg">
        <q-btn
          flat
          sm
          no-caps
          color="primary"
          @click="createAccount"
          >
          {{$t('login__register')}}
        </q-btn>
      </div>
    
      <div
        v-if="isTelegramApp"
        id="alt_login"
        class="w80 q-flex column items-center q-pt-xl"
        >
        <div
          class="orline w100 text-grey"
          >
          <span class="q-mx-sm">{{$t('login__or_continue_as')}}</span>
        </div>
        <q-btn
          flat
          sm
          no-caps
          color="primary"
          :disabled="!acceptTermsOfUse || !isEmailValid || !isPasswordValid"
          @click="handleTelegramLogin"
          >
          <div class="flex items-center text-blue">
            <q-icon name="telegram" size="md" class="q-mx-none text-blue"/>
            <div class="q-ml-xs ellipsis" style="max-width: 100px">
              {{
              tgUser?.first_name + 
              (tgUser?.first_name && tgUser?.last_name ? ' ' : '') +
              tgUser?.last_name
              }}
            </div>
          </div>
        </q-btn>
      </div>
    </q-card>

    <div
      id="term-of-use"
      class="absolute-bottom q-py-lg text-white flex justify-center row"
      >
      <q-checkbox
        v-model="acceptTermsOfUse"
        checked-icon="task_alt"
        unchecked-icon="highlight_off"
        :color="acceptTermsOfUse ? 'brand' : 'red'"
        dense
        keep-color
      />
      <span class="q-px-xs">
        {{ $t('login__accept_terms_of_use') + ' ' }}
      </span>
      <span
        @click="router.push('terms-of-use')"
        style="text-decoration: underline;"
        >
        {{ $t('login__terms_of_use') }}
      </span>
    </div>
  </q-page>
</template>

<script setup lang="ts">
  import { ref, computed, inject, onUnmounted } from 'vue'
  import { useQuasar } from 'quasar'
  import { useRouter } from 'vue-router'
  import loginLogo from 'components/login-page/loginLogo.vue'
  import { useI18n } from "vue-i18n"
  import { useAuthStore } from 'src/stores/auth'
  import type { WebApp } from '@twa-dev/types'
  import { QInput } from 'quasar'
  import type { ServerError } from 'boot/axios'

  type ValidationRule = (val: string) => boolean | string
  
  const tg = inject('tg') as WebApp
  const tgUser = tg.initDataUnsafe.user
    
  const authStore = useAuthStore()
  const router = useRouter()
  const $q = useQuasar()
  const { t } = useI18n()

  const login = ref<string>('')
  const password = ref<string>('')
  const isPwd = ref<boolean>(true)
  const acceptTermsOfUse = ref<boolean>(true)

  const emailInput = ref<InstanceType<typeof QInput>>()
  const passwordInput = ref<InstanceType<typeof QInput>>()

  const validationRules = {
    email: [(val: string) => /.+@.+\..+/.test(val) || t('login__incorrect_email')] as [ValidationRule],
    password: [(val: string) => val.length >= 8 || t('login__password_require')] as [ValidationRule]
  }

  const isEmailValid = computed(() => 
    validationRules.email.every(f => f(login.value) === true)
  )

  const isPasswordValid = computed(() => 
    validationRules.password.every(f => f(password.value) === true)
  )

  const passwordHint = computed(() => {
    const result = validationRules.password[0](password.value)
    return typeof result === 'string' ? result : ''
  })

  // fix validity problem with router.push
  type Field = 'login' | 'password'

  const validateTimerId = ref<Record<Field, ReturnType<typeof setTimeout> | null>>({
    login: null,
    password: null
  })
  
  const delayValidity = (type: Field) => {
    validateTimerId.value[type] = setTimeout(() => {
      void (async () => {
        if (validateTimerId.value[type] !== null) {
          clearTimeout(validateTimerId.value[type])
        }
        if (type === 'login') await emailInput.value?.validate()
        if (type === 'password') await passwordInput.value?.validate()
      })()
    }, 300)
  }

  function onErrorLogin (error: ServerError) {
    $q.notify({
      message: t(error.message) + ' (' + t('code') + ':' + error.code + ')',
      type: 'negative',
      position: 'bottom',
      timeout: 2000,
      multiLine: true
    })
  }

  async function sendAuth() {
    try { void await authStore.loginWithCredentials(login.value, password.value) }
    catch (error) {
      console.log(error)
      onErrorLogin(error as ServerError)
    }
    await router.push({ name: 'projects' })
  }

  
  async function forgotPwd() {
    sessionStorage.setItem('pendingLogin', login.value)
    await router.push({ name: 'recovery_password' })
  }

  async function createAccount() {
    sessionStorage.setItem('pendingLogin', login.value)
    await router.push({ name: 'create_account' })
  }

  const isTelegramApp = computed(() => {
      // @ts-expect-ignore
      return !!window.Telegram?.WebApp?.initData
    })

  /* const handleSubmit = async () => {
    await authStore.loginWithCredentials(email.value, password.value)
  } */

async function handleTelegramLogin () {
  // @ts-expect-ignore
  const initData = window.Telegram.WebApp.initData
  await authStore.loginWithTelegram(initData)
}

onUnmounted(() => {
  Object.values(validateTimerId.value).forEach(timer => timer && clearTimeout(timer))
})
  
</script>

<style scoped>

  .maxh15 {
    max-height: calc(100Vh *0.15);
  }

  .input-login {
    width: calc(100% * 0.8);
    max-width: 300px;
  }

  .orline {
    display: flex;
    flex-direction: row;
  }     

  .orline:before,
  .orline:after {
      content: "";
      flex: 1 1;
      border-bottom: 1px solid;
      margin: auto;
  }

  .login-card {
    opacity: 0.9 !important;
    border-radius: var(--top-raduis);
  }
</style>
