import { serv_constants } from '@store/Modules/serv_constants'

import { tools } from '@tools'
import { Logo } from '../../components/logo'
import { CTitleBanner } from '../../components/CTitleBanner'

import { defineComponent, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from '@store/globalStore'
import { useQuasar } from 'quasar'
import useVuelidate from '@vuelidate/core'
import { useRoute, useRouter } from 'vue-router'

import { minLength, required, sameAs } from '@vuelidate/validators'
import { computed } from 'vue'
import { complexity } from '../../validation'


export default defineComponent({
  name: 'UpdatePassword',
  components: { Logo, CTitleBanner },
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const $router = useRouter()
    const $route = useRoute()

    const typePassword = ref('password')

    const emailsent = ref(false)
    const form = reactive({
      password: '',
      repeatPassword: '',
      tokenforgot: '',
      email: '',
      idapp: ''
    })

    const validations: any = computed(() => {
      return {
        password: {
          required,
          minLength: minLength(8),
          complexity,
        },
        repeatPassword: {
          required,
          repeatPassword: sameAs(form.password),
        }
      }
    })

    // @ts-ignore
    const v$ = useVuelidate(validations, form)

    function submit() {
      v$.value.$touch()

      if (v$.value.$error) {
        tools.showNotif($q, t('reg.err.errore_generico'))
        return
      }

      $q.loading.show({ message: t('reset.incorso') })

      // console.log('$route.query', $route.query)
      if ($route.query.tokenforgot) {
        form.tokenforgot = $route.query.tokenforgot.toString()
      }
      if ($route.query.email) {
        form.email = $route.query.email.toString()
      }
      form.idapp = tools.getEnv('VITE_APP_ID') ? tools.getEnv('VITE_APP_ID') : '1'

      console.log(form)
      userStore.resetpwd(form)
        .then((ris: any) => {
          console.log('ris', ris)
          if (ris.code === serv_constants.RIS_CODE_OK)
            $router.push('/signin')
          else if (ris.code === serv_constants.RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND)
            tools.showNegativeNotif($q, t('reset.token_scaduto'))
          else
            tools.showNegativeNotif($q, t('fetch.errore_server'))

          $q.loading.hide()
        })
        .catch(e => {
          console.log('ERROR = ' + e)
          $q.loading.hide()
        })

    }

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


    return {
      form,
      emailsent,
      submit,
      tools,
      v$,
      showPassword,
      typePassword,
    }
  }
})
