import { tools } from '@tools'

import type { ISignupOptions } from 'model'

import { Logo } from '@src/components/logo'

// import 'vue-country-code/dist/vue-country-code.css'

import { CTitleBanner } from '../CTitleBanner'
import { CCopyBtn } from '../CCopyBtn'
import { CRegistration } from '../CRegistration'
import { PagePolicy } from '../PagePolicy'
import { computed, defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { CSignIn } from '@src/components/CSignIn'
import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { DefaultProfile, useUserStore } from '@store/UserStore'
import useValidate from '@vuelidate/core'
import useVuelidate from '@vuelidate/core'

import { shared_consts } from '@src/common/shared_vuejs'

import { minLength, required, sameAs } from '@vuelidate/validators'

// import { ValidationRuleset } from 'vuelidate'
import { complexity, complexityUser, registereduser, aportadorexist } from '../../validation'

// import 'vue3-tel-input/dist/vue3-tel-input.css'
import { useRoute, useRouter } from 'vue-router'
import { static_data } from '@src/db/static_data'
import { useGlobalStore } from '@store/globalStore'

// import {Loading, QSpinnerFacebook, QSpinnerGears} from 'quasar'

export default defineComponent({
  name: 'CSignUp',
  components: { Logo, CTitleBanner, PagePolicy, CCopyBtn, CRegistration },
  props: {
    showadultcheck: {
      type: Boolean,
      required: false,
      default: false,
    },
    showcell: {
      type: Boolean,
      required: false,
      default: false,
    },
    showaportador: {
      type: Boolean,
      required: false,
      default: false,
    },
    shownationality: {
      type: Boolean,
      required: false,
      default: false,
    },
    show_namesurname: {
      type: Boolean,
      required: false,
      default: true,
    },
    regexpire: {
      type: String,
      required: false,
      default: '',
    },
    name_default: {
      type: String,
      required: false,
      default: '',
    },
    username_default: {
      type: String,
      required: false,
      default: '',
    },
    need_Telegram: {
      type: Boolean,
      required: false,
      default: false,
    },
    collettivo: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()
    const userStore = useUserStore()
    const $route = useRoute()
    const $router = useRouter()

    const countryname = ref('')
    const iamadult = ref(false)
    const duplicate_email = ref(false)
    const duplicate_username = ref(false)
    const visureg = ref(false)
    const showpolicy = ref(false)
    const visubuttBOT = ref(false)
    const isalreadyReg = ref(false)
    const needTelegram = ref(false)
    const slide = ref('1')
    const inputAportador = ref(<any>null)
    const inputEmail = ref(<any>null)
    const inputUsername = ref(<any>null)
    const inputName = ref(<any>null)
    const inputSurname = ref(<any>null)
    const inputPassword = ref(<any>null)
    const inputPassword2 = ref(<any>null)

    const checkifDisabled = computed(() => {
      let ret = true
      if (slide.value === '1') {
        // Invitante + Email
        ret = !signup.email || (tools.getAskToVerifyReg() && (!signup.aportador_solidario || inputAportador.value.hasError)) || (inputEmail.value && inputEmail.value.hasError)
      } else if (slide.value === '2') {
        // Username
        ret = !signup.username || (inputUsername.value && inputUsername.value.hasError)

        if (tools.getConfSiteOptionEnabled(shared_consts.ConfSite.regNameSurnameMandatory)) {
          ret = ret || (!signup.name || (inputName.value && inputName.value.hasError))
          ret = ret || (!signup.surname || (inputSurname.value && inputSurname.value.hasError))
        }
      } else if (slide.value === '3') {
        // Password
        ret = !signup.password || (!inputPassword.value || (inputPassword.value && inputPassword.value.hasError)) || (!inputPassword2.value || (inputPassword2.value && inputPassword2.value.hasError))
      }

      return ret
    })

    const typePassword = ref('password')

    const ap_iniziale = ref('')

    const globalStore = useGlobalStore()
    const site = computed(() => globalStore.site)

    const signup = reactive(<ISignupOptions>{
      email: '',
      username: '',
      name: '',
      surname: '',
      password: '',
      repeatPassword: '',
      terms: false,
      profile: DefaultProfile,
      aportador_solidario: '',
    })

    const validations: any = computed(() => {
      const valid: any = {
        repeatPassword: {
          required,
          repeatPassword: sameAs(signup.password),
        },
        password: {
          required,
          minLength: minLength(8),
          complexity,
        },
        username: {
          required,
          minLength: minLength(4),
          complexityUser,
          registereduser,
        },
        name: {
          required: (props.collettivo || tools.getConfSiteOptionEnabled(shared_consts.ConfSite.regNameSurnameMandatory)) ? true : false,
        },
        surname: {
          required: (tools.getConfSiteOptionEnabled(shared_consts.ConfSite.regNameSurnameMandatory)) ? true : false,
        },
        terms: {
          required,
        },
        aportador_solidario: {
          aportadorexist,
          required
        }
      }

      if (props.show_namesurname) {
        valid.name = {

        }
        valid.surname = {

        }
      }

      return valid
    })

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

    const invited = ref($route.params.invited)
    const usernameteleg = ref($route.params.usernameteleg)
    const idteleg = ref($route.params.idteleg)

    watch(() => slide.value, (to: any, from: any) => {
      if (slide.value === '3') {
        v$.value.$touch()
      }
    })

    watch(() => invited, (to: any, from: any) => {
      if (props.showaportador) {
        console.log('changeaportador', $route.params.invited)
        if (!signup.aportador_solidario) {
          if ($route.params.invited) {
            // @ts-ignore
            signup.aportador_solidario = $route.params.invited
          }
        }
      }
    })

    function allowSubmit() {

      let error = v$.value.$error || v$.value.$invalid || globalStore.serverError

      if (props.showadultcheck)
        error = error || !iamadult.value

      if (props.showcell) {
        if (signup.profile)
          error = error || signup.profile.cell!.length <= 6
        else
          error = true
      }

      if (tools.getAskToVerifyReg()) {
        error = error || !signup.aportador_solidario
      }

      return !error
    }

    function env() {
      return process.env
    }


    function changeemail() {
      signup.email = tools.removespaces(signup.email!)
      signup.email = signup.email.toLowerCase()
      emit('update:value', signup.email)
    }

    function changeusername(value: string) {
      signup.username = tools.removespaces(signup.username)
      emit('update:value', signup.username)
    }

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

      signup.email = tools.removespaces(signup.email!)
      signup.email = signup.email.toLowerCase()
      signup.username = tools.removespaces(signup.username)

      // remove @
      signup.username = tools.removeAt(signup.username)

      duplicate_email.value = false
      duplicate_username.value = false

      if (!signup.terms) {
        tools.showNotif($q, t('reg.err.terms'))
        return
      }

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

      if (signup.name) {
        signup.name = tools.CapitalizeAllWords(signup.name)
        signup.surname = tools.CapitalizeAllWords(signup.surname)
      }

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

      console.log(signup)
      return userStore.signup(tools.clone(signup))
        .then((ris: any) => {
          if (tools.SignUpcheckErrors($q, $router, ris.code, ris.msg))
            $q.loading.hide()
        }).catch((error: string) => {
          console.log('ERROR = ' + error)
          $q.loading.hide()
        })

    }

    function intcode_change(coderec: any) {
      // console.log('intcode', coderec)
      if (signup.profile) {
        signup.profile.intcode_cell = '+' + coderec.dialCode
        signup.profile.iso2_cell = coderec.iso2
      }
    }

    function selectcountry({ name, iso2, dialCode }: { name: string, iso2: string, dialCode: string }) {
      // console.log(name, iso2, dialCode)
      signup.profile.nationality = iso2
      countryname.value = name
    }


    async function created() {

      needTelegram.value = props.need_Telegram

      console.log('$route.params', $route.params)

      ap_iniziale.value = $route.params.invited ? $route.params.invited.toString() : ''

      signup.aportador_solidario = $route.params.invited ? $route.params.invited.toString() : ''
      signup.username = $route.params.usernameteleg ? $route.params.usernameteleg.toString() : ''
      signup.regexpire = $route.params.regexpire ? $route.params.regexpire.toString() : props.regexpire
      if (signup.username)
        isalreadyReg.value = await tools.registeredusername(signup.username)
      signup.profile.username_telegram = signup.username
      if ($route.params.idteleg) {
        signup.profile.teleg_id = $route.params.idteleg ? parseInt($route.params.idteleg.toString(), 10) : 0
      }

      if (props.collettivo) {
        signup.username = props.username_default!
        signup.name = props.name_default!
      }

      // console.log('1) aportador_solidario', signup.aportador_solidario)

      if (!signup.aportador_solidario)
        signup.aportador_solidario = tools.getCookie(tools.APORTADOR_SOLIDARIO, signup.aportador_solidario)

      if (!signup.aportador_solidario || signup.aportador_solidario === 'undefined') {
        if (!tools.getAskToVerifyReg()) {
          signup.aportador_solidario = tools.APORTADOR_NONE
        }
      }

      // console.log('signup.aportador_solidario', signup.aportador_solidario)
      // console.log('getasktoverify', tools.getAskToVerifyReg())

      if (tools.getAskToVerifyReg()) {

        if (!signup.username || !signup.profile.teleg_id) {
          // tools.copyStringToClipboard($q, signup.aportador_solidario, true)
          visubuttBOT.value = true
          // window.location.href = tools.getLinkBotTelegram()
        }
      }
    }

    function myRuleEmail(val: string) {

      return new Promise((resolve, reject) => {
        // call
        //  resolve(true)
        //     --> content is valid
        //  resolve(false)
        //     --> content is NOT valid, no error message
        //  resolve(error_message)
        //     --> content is NOT valid, we have error message
        tools.registeredemail(val).then((emailOk) => {
          let risp = !!emailOk || t('reg.err.duplicate_email')
          if (emailOk) {
            risp = tools.isEmail(val) || t('reg.err.invalid_email')
            emailOk = emailOk && tools.isEmail(val)
          }
          if (emailOk) {
            // risp = !tools.isEmailNoMicroZozz(val) || t('reg.err.invalid_email_micro')
          }

          resolve(risp)

        })

        // calling reject(...) will also mark the input
        // as having an error, but there will not be any
        // error message displayed below the input
        // (only in browser console)
      })

    }

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

    function regEventEmail(invited: boolean) {
      console.log('EVENT RECEIVED: regEventEmail', invited)
      // reg
      visubuttBOT.value = false
      needTelegram.value = false

    }

    created()

    return {
      changeemail,
      changeusername,
      submitOk,
      selectcountry,
      intcode_change,
      tools,
      countryname,
      signup,
      iamadult,
      v$,
      t,
      allowSubmit,
      myRuleEmail,
      visureg,
      showpolicy,
      visubuttBOT,
      isalreadyReg,
      site,
      showPassword,
      typePassword,
      ap_iniziale,
      regEventEmail,
      needTelegram,
      slide,
      checkifDisabled,
      inputAportador,
      inputEmail,
      inputUsername,
      inputName,
      inputSurname,
      inputPassword,
      inputPassword2,
      shared_consts,

    }
  },
})
