<template>
  <q-page
    class="q-ma-none w100"
    >
    <q-scroll-area
      style="height: 100vh"
      >
      <div
        class="w100 flex justify-center items-center"
        style="min-height: 100vh;"
        >
        <div
          id="login_block"
          style="max-width: 300px;"
          >
          <div class="flex column no-wrap items-center">
            <div class="q-pb-lg">
              <base-logo
                :withBackground = "false"
                animated
                class="text-h5"
              />
            </div>

            <div class="flex column w100">
              <q-input
                v-model.trim="login"
                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.trim="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 rounded
                  class="text-grey"
                  >
                  <span class="q-px-sm">
                    {{ $t('login__forgot_password') }}
                  </span>
                </q-btn>
              </div>
            </div>
              <q-btn
                @click="sendAuth()"
                color="primary"
                class="w100 q-my-md fix-disabled-btn"
                :disabled="!isEmailValid || !isPasswordValid"
                :unelevated="!isEmailValid || !isPasswordValid"
                rounded
                >
                {{ $t('login__sign_in') }}
              </q-btn>

              <q-btn
                flat rounded
                sm no-caps
                class="q-my-md w100"
                color="primary"
                @click="createAccount"
                >
                {{ $t('login__register') }}
              </q-btn>
          
            <div
              v-if="isTelegramApp"
              id="alt_login"
              class="flex w100 column items-center "
              >
              <div class="orline w100 text-grey"> 
                <span class="q-mx-sm text-caption">
                  {{ $t('login__or_continue_as') }}
                </span>
              </div>
              <q-btn
                flat rounded
                sm no-caps
                color="primary"
                class="q-mt-md w100"
                @click="handleTelegramLogin"
                >
                <pn-account-block-name class="flex justify-center"/>
              </q-btn>
            </div>
          </div>
        </div>
      </div>
    </q-scroll-area>
  </q-page>
</template>

<script setup lang="ts">
  import { ref, computed, inject, onUnmounted } from 'vue'
  import { useRouter } from 'vue-router'
  import baseLogo from 'components/BaseLogo.vue'
  import { useInputRules } from 'composables/useInputRules'
  import { useAuthStore } from 'stores/auth'
  import { useSettingsStore } from 'stores/settings'
  import { QInput } from 'quasar'
  import type { WebApp } from '@twa-dev/types'

  const tg = inject('tg') as WebApp
    
  const authStore = useAuthStore()
  const settingsStore = useSettingsStore()
  const router = useRouter()
  const { inputRules } = useInputRules()

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

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

  const validationRules = {
    email: [inputRules.email],
    password: [inputRules.password]
  }

  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] ? validationRules.password[0](password.value) : null
    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' && login.value !== '') await emailInput.value?.validate()
        if (type === 'password' && password.value !== '') await passwordInput.value?.validate()
      })()
    }, 500)
  }

  async function sendAuth() {
    try {
      await authStore.loginWithCredentials(login.value, password.value, tg.initData, settingsStore.settings.locale)
      await router.push({ name: 'projects' })
    }
    catch (error) {
      console.error('Login failed:', error)
    }
  }
    
  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
    })

  async function handleTelegramLogin () {
    try {
      await authStore.loginWithTelegram(tg.initData)
      await router.push({ name: 'projects' })
    } catch {
      await router.push({ name: 'agreements', query: { type: 'register' }})
    }
  }

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

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