import { defineComponent, PropType, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from '@store/globalStore'
import { useQuasar } from 'quasar'

import { validationMixin } from 'vuelidate'
import { Logo } from '../logo'
import { CCheckAppRunning } from '../CCheckAppRunning'
import { static_data } from '@src/db/static_data'
import { tools } from '@tools'
import type { ISigninOptions } from 'model'
import { serv_constants } from '@store/Modules/serv_constants'
import { useRouter } from 'vue-router'

// import { useFormChild } from 'quasar'

export default defineComponent({
  name: 'CSignIn',
  components: { Logo, CCheckAppRunning },
  props: {
    showregbutt: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()
    const userStore = useUserStore()
    const $router = useRouter()
    const globalStore = useGlobalStore()

    const enablePwa = computed(() => globalStore.site.confpages.enablePwa)

    const refUsername = ref(<any>null)
    const refPassword = ref(null)

    const loading = ref(false)
    const autoCompleteTriggered = ref(true)
    const wasblank = ref(false)

    const site = computed(() => {
      return globalStore.site
    })

    const myForm = ref(null)

    const typePassword = ref('password')

    const iswaitingforRes = ref(false)
    const signin = ref(<ISigninOptions>{
      username: '',
      password: '',
    })

    function onReset() {
      signin.value.username = ''
      signin.value.password = ''
    }


    function created() {
      onReset()

      if (userStore.resStatus === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
        emit('showNotif', 'fetch.error_doppiologin')
      }

    }

    function getlinkforgetpwd() {
      return '/requestresetpwd'
    }

    function isError() {
      if (refUsername.value) {
        // @ts-ignore
        return refUsername.value.hasError
      }
    }

    function onSubmit() {

      if (refUsername.value) {
        refUsername.value.validate()
      }

      // console.log('submit LOGIN')

      signin.value.username = tools.removespaces(signin.value.username)

      // $v.signin.$touch()

      if (isError()) {
        emit('showNotif', 'reg.err.errore_generico')
        return
      }

      emit('loginInCorso')

      // disable Button Login:
      iswaitingforRes.value = true

      if (import.meta.env.VITE_DEBUG) {
        // console.log('signin', signin)
      }

      userStore.signin($router, signin.value)
        .then((riscode: any) => {
          console.log('signin FINITO CALL: riscode=', riscode)
          tools.checkApp()

          if ($q.screen.lt.sm) {
            //  globalStore.setleftDrawerOpen(false)
          }
          if (riscode === tools.OK) {
            if (userStore.isLogged) {
              globalStore.rightDrawerOpen = false
            }
            // router.push('/signin')
          }
          return riscode
        })
        .then((riscode: number) => {
          if (import.meta.env.VITE_DEBUG) {
            // console.log('  riscode(1) =', riscode)
          }

          return riscode
        })
        .then((riscode: number) => {
          if (riscode === tools.OK) {
            console.log('  -> eseguo emit(loginOk)')

            emit('loginOk')

            globalStore.createPushSubscription()

          } else {
            console.log('  -> eseguo emit(checkErrors)')
            emit('checkErrors', riscode)
          }

          console.log('iswaitingforRes FALSE')
          iswaitingforRes.value = false

        })
        .catch((err: any) => {
          console.log('ERROR SIGNIN = ' + err)

          emit('checkErrors', err)
        })
      // console.log('   END submit')
    }

    function showPassword() {
      //
      typePassword.value = typePassword.value === 'password' ? 'text' : 'password'
    }

    function checkAutoCompletion() {

      // Check if the password field value changes without user input
      if (signin.value.password.length <= 2) {
        wasblank.value = true
        autoCompleteTriggered.value = false;
      }

      if (signin.value.password.length > 0 && !autoCompleteTriggered.value && !wasblank.value) {
        // Auto-completion was executed
        console.log('Auto-completion executed.');
        autoCompleteTriggered.value = true;
      }
    }
    created()

    return {
      static_data,
      refUsername,
      onReset,
      onSubmit,
      signin,
      getlinkforgetpwd,
      myForm,
      site,
      showPassword,
      typePassword,
      enablePwa,
      checkAutoCompletion,
      autoCompleteTriggered,
    }
  },
})
