import type { PropType } from 'vue';
import { defineComponent, onMounted, ref, watch, computed } from 'vue'
import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from '@store/globalStore'
import type { ICircuit, IUserFields } from 'model';
import { IImgGallery, IUserProfile } from 'model'
import { costanti } from '@costanti'
import { shared_consts } from '@src/common/shared_vuejs'
import { tools } from '@tools'
import { useQuasar } from 'quasar'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CSendCoins } from '@src/components/CSendCoins'
import { CSkill } from '@src/components/CSkill'
import { CMyFieldRec } from '@src/components/CMyFieldRec'
import { CSaldo } from '@src/components/CSaldo'
import { CMySelectCity } from '@src/components/CMySelectCity'
import { CMyFieldDb } from '@src/components/CMyFieldDb'
import { CMyCircuit } from '@src/components/CMyCircuit'
import { CMySelect } from '@src/components/CMySelect'
import { CMyUserOnlyView } from '@src/components/CMyUserOnlyView'
import { CMyUser } from '@src/components/CMyUser'
import { CUserInfoAccount } from '@src/components/CUserInfoAccount'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { useCircuitStore } from '@store/CircuitStore'

const STEP_CITY = 100
const STEP_CIRCUIT = 200
const STEP_CIRCUIT_ITALIA = 210
const STEP_FINE = 400
const STEP_NAME_SURNAME = 401
const STEP_FOTO = 402

export default defineComponent({
  name: 'CMyProfileTutorial',
  components: {
    CSendCoins, CSaldo, CUserInfoAccount,
    CMySelectCity, CMyFieldRec, CMyUser,
    CSkill, CMyUserOnlyView, CTitleBanner, CMySelect, CMyFieldDb, CMyCircuit
  },
  emits: ['setCmd'],
  props: {
    mycontact: {
      type: Object as PropType<IUserFields | null>,
      required: false,
      default: null,
    },
    myusername: {
      type: String,
      required: false,
      default: null,
    },
  },

  setup(props, { emit }) {

    const userStore = useUserStore()
    const circuitStore = useCircuitStore()
    const globalStore = useGlobalStore()
    const $q = useQuasar()
    const { t } = useI18n()
    const $router = useRouter()
    const $route = useRoute()

    const showAccountInfo = ref(false)
    const indstep = ref(0)
    const step = ref(1)
    const nascondiavviso = ref(false)

    const username = ref('')
    const showsendCoinTo = ref(false)
    const circuitsel = ref('')
    const mycircuit = ref(<ICircuit | undefined | null>null)
    const circuititalia = ref(<ICircuit | undefined | null>null)
    const mylistcircuits = ref(<ICircuit[] | undefined>[])

    const contact = ref(<IUserFields | null>null)

    const filtroutente = ref(<any[]>[])
    const showBanner_utenti_verif = ref(true)

    const usersList = ref({ show: false, title: '', list: [] })

    const stepTut = computed(() => userStore.my.profile.stepTutorial)
    const noNameSurname = computed(() => userStore.my.profile.noNameSurname)

    const mycards = computed(() => {
      return costanti.MAINCARDS.filter((rec: any) => shared_consts.TABLES_INSERT_ALMOST_ONE_TO_ENABLE_CIRCUIT.includes(rec.table))
    })

    const userstoverify = computed(() => {
      return userStore.my.profile.userstoverify
    })

    const strProv = computed(() => {

      if (contact.value && contact.value.profile.resid_province) {
        return contact.value.profile.resid_province
      } else {
        return ''
      }
    })

    const card = computed(() => {

      if (contact.value && contact.value.profile.resid_card) {
        return contact.value.profile.resid_card
      } else {
        return ''
      }
    })

    watch(() => strProv.value, (newval: string, oldval: string) => {
      mycircuit.value = circuitStore.getCircuitByProvinceAndCard(strProv.value, card.value)
      if (!globalStore.isPresenteCardsByProv(strProv.value)) {
        if (contact.value && contact.value.profile.resid_card) {
          contact.value.profile.resid_card = ''
        }
      }
    })

    watch(() => card.value, (newval: string, oldval: string) => {
      mycircuit.value = circuitStore.getCircuitByProvinceAndCard(strProv.value, card.value)
    })

    watch(() => circuitsel.value, (newval: string, oldval: string) => {
      if (circuitsel.value)
        mycircuit.value = circuitStore.getCircuitByName(circuitsel.value)
    })


    const arrStep = ref([
      {
        indstep: 0,
        step: STEP_CITY,
        title: t('tutorial.step_residence_title'),
        extratitle: function () { return ': ' + (contact.value!.profile.resid_province ? contact.value!.profile.resid_province : '') },
        label: t('tutorial.step_residence'),
        checkOk: function (): boolean { return contact.value ? !!contact.value.profile.resid_province && contact.value.profile.resid_province !== '' && contact.value.profile.resid_province !== '0' : false },
        checkOkReal: function (): boolean { return this.checkOk() },
        icon: 'house',
        required: true,
      },
      /*{
        step: STEP_NAME_SURNAME,  // 2
        title: t('tutorial.step_nomecognome_title'),
        extratitle: function () { return ': ' + (contact.value ? tools.getNomeUtenteEUsernameByRecUser(contact.value) : '') },
        label: t('tutorial.step_nomecognome'),
        checkOk: function () { return ((contact.value ? !!contact.value.name : false) || userStore.my.profile.noNameSurname) },
        checkOkReal: function () { return ((contact.value ? !!contact.value.name : false)) },
        icon: 'user',
        required: false,
      },*/
      {
        indstep: 1,
        step: STEP_CIRCUIT,
        title: t('tutorial.step_circuito_title'),
        extratitle: function () { return mycircuit.value ? ': ' + mycircuit.value.name : '' },
        label: t('tutorial.step_circuito'),
        label_ok: t('tutorial.step_circuito_ok'),
        checkOk: function () {
          if (mycircuit.value) {
            return ((userStore.IsMyCircuitByName(mycircuit.value.name) ||
              userStore.IsAskedCircuitByName(mycircuit.value.name))) || (userStore.my.profile.noCircuit)
          }
          return false
        },
        checkOkReal: function () {
          if (mycircuit.value) {
            return ((userStore.IsMyCircuitByName(mycircuit.value.name) ||
              userStore.IsAskedCircuitByName(mycircuit.value.name)))
          }
          return false
        },
        icon: 'img: /images/1ris_rosso_100.png',
        required: false,
      },
      /*{
        step: 3,
        title: t('tutorial.step_beniservizi_title'),
        extratitle: function () { return ': (' + userStore.my.profile.calc.numGoodsAndServices + ')' },
        label: t('tutorial.step_beniservizi'),
        checkOk: function () {
          return userStore.my.profile.calc.numGoodsAndServices! > 0
        },
        checkOkReal: function () { return this.checkOk() },
        icon: 'fas fa-tshirt',
        required: false,
      },*/
      /*{
        step: STEP_FOTO,
        title: t('tutorial.step_profilo_title'),
        extratitle: function () { return ': (' + (userStore.my.profile.img ? t('dialog.yes') : t('dialog.no')) + ')' },
        label: t('tutorial.step_profilo'),
        checkOk: function () {
          return !!userStore.my.profile.img
        },
        checkOkReal: function () { return this.checkOk() },
        icon: 'fas fa-tshirt',
        required: false,
      },*/
    ])

    const numindstep = computed(() => arrStep.value.length)


    watch(() => indstep.value, (newval: number, oldval: number) => {
      if (indstep.value >= 0 && arrStep.value.length > indstep.value && arrStep.value[indstep.value])
        step.value = arrStep.value[indstep.value].step
      else
        step.value = 0

      if (indstep.value > userStore.my.profile.stepTutorial)
        userStore.my.profile.stepTutorial = indstep.value

      userStore.saveStepTutorial(indstep.value)
      if (indstep.value >= numindstep.value) {
        tools.scrollToTop()
      }

      if ((step.value === STEP_CIRCUIT)) {
        mycircuit.value = circuitStore.getCircuitByProvinceAndCard(strProv.value, card.value)

        mylistcircuits.value = circuitStore.getCircuitsNameByProvince(strProv.value)
        console.log('isAskedToCircuit()', isAskedToCircuit())
        // userStore.savenoCircuit(isAskedToCircuit())
      }

      if ((step.value === STEP_CIRCUIT_ITALIA)) {
        mylistcircuits.value = []
        circuititalia.value = circuitStore.getCircuitByPath('ris_italia')
      }

      if (step.value === STEP_NAME_SURNAME + 1) {
        const index = indstep.value
        console.log('Salva ', arrStep.value[index])
        if ((contact.value ? !!contact.value.name : false) && contact.value!.name) {
          // nome esistente
          userStore.savenoNameSurname(false)
        } else {
          userStore.savenoNameSurname(true)
        }
      }

      /*if (step.value === STEP_FOTO + 1) {
        let index = indstep.value
        if (userStore.my.profile.img) {
          // foto esistente
          userStore.savenoFoto(false)
        } else {
          userStore.savenoFoto(true)
        }
      } */

    })


    const stepFine = {
      step: STEP_FINE,
      title: t('tutorial.step_fine_title'),
      extratitle: function () { return '' },
      label: t('tutorial.step_fine'),
      checkOk: function () {
        return true
      },
      checkOkReal: function () { return this.checkOk() },
      icon: 'fas fa-tshirt',
      required: false,
    }


    const stepCircItalia =
    {
      step: STEP_CIRCUIT_ITALIA,
      title: t('tutorial.step_circuito_italia_title'),
      extratitle: function () { return circuititalia.value ? ': ' + circuititalia.value.name : '' },
      label: circuitStore.SonoDentroAdAlmeno1CircuitoConFido() ? t('tutorial.step_circuito_italia') : t('tutorial.non_sono_dentro_al_mio_circuito'),
      label_ok: t('tutorial.step_circuito_italia_ok'),
      checkOk: function () {
        if (circuititalia.value) {
          return ((userStore.IsMyCircuitByName(circuititalia.value.name) ||
            userStore.IsAskedCircuitByName(circuititalia.value.name))) || userStore.my.profile.noCircIta
        }
        return false
      },
      checkOkReal: function () {
        if (circuititalia.value) {
          return ((userStore.IsMyCircuitByName(circuititalia.value.name) ||
            userStore.IsAskedCircuitByName(circuititalia.value.name)))
        }
        return false
      },
      icon: 'img: /images/1ris_rosso_100.png',
      required: false,
    }


    const prStep = computed(() => {

      let num = 0
      for (const mystep of arrStep.value) {
        if (mystep.checkOk())
          num++
        else
          break
      }
      return num
    })

    const progressStep = computed(() => {

      if (numindstep.value > 0)
        return prStep.value / numindstep.value
      else
        return 0
    })

    const progressLabel = computed(() => (progressStep.value * 100).toFixed(0) + '%')

    watch(() => props.mycontact, (newval, oldval) => {
      updatestart()
    })

    watch(() => tools.isUserOk(), (newval, oldval) => {
      if (userStore.isUserOk()) {
        updatestart()
      }
    })

    function updatestart() {
      if (!props.mycontact) {
        if (props.myusername) {
          username.value = props.myusername
          //++Todo: carica contact
          contact.value = null
        } else {
          contact.value = userStore.my
        }
      } else {
        if (props.mycontact) {
          contact.value = props.mycontact
          username.value = props.mycontact.username
        }
      }
      if (contact.value && contact.value.profile && contact.value.profile.resid_province === '0') {
        contact.value.profile.resid_province = ''
      }

      mylistcircuits.value = circuitStore.getCircuitsNameByProvince(strProv.value)

      mycircuit.value = circuitStore.getCircuitByProvinceAndCard(strProv.value, card.value)

      if (contact.value)
        if (contact.value)
          filtroutente.value = [{ userId: contact.value._id }]

      userStore.my.profile.stepTutorial = getFirstStepToFill()

      indstep.value = userStore.my.profile.stepTutorial ? userStore.my.profile.stepTutorial : 0
      if (indstep.value > numindstep.value)
        indstep.value = numindstep.value

      // console.log('indstep.value', indstep.value)

      // circuit.value = circuitStore.getCircuitByName(props.circuitname)

      if (!userStore.my.profile.stepTutorial || userStore.my.profile.stepTutorial === 0) {
        userStore.my.profile.stepTutorial = 0
      }


    }


    function getFirstStepToFill() {
      let num = 0
      for (const mystep of arrStep.value) {
        if (mystep.checkOk())
          num++
        else
          break
      }

      return num
    }

    function getImgUser(profile: IUserFields) {
      return userStore.getImgByProfile(profile)
    }

    function naviga(path: string) {
      $router.push(path)
    }

    function setCmd($q: any, cmd: number, myusername: string, value: any, dest: string) {
      emit('setCmd', $q, cmd, myusername, value, dest)
    }

    function getLabelByStatusStep(step: string) {
      const mystr = ''

      return mystr

    }

    const checkifDisabled = computed(() => {
      const ret = true
      const mystep = indstep.value
      if (mystep > 0) {
        return !arrStep.value[mystep].checkOk()
      } else {
        return false
      }
    })

    function clickFinish() {
      userStore.my.profile.stepTutorial = numindstep.value + 1
      indstep.value = numindstep.value + 1

    }

    function getindstepByStep(step: number) {
      for (let indstep = 0; indstep < arrStep.value.length; indstep++) {
        if (arrStep.value[indstep].step === step)
          return indstep
      }
      return -1
    }

    function isNextDisable(step: number) {
      try {
        const indstep = getindstepByStep(step)
        if (indstep >= 0)
          return arrStep.value[indstep].required && !arrStep.value[indstep].checkOk()
        return false
      } catch (e) {
        return false
      }
    }

    function numStepCompleted() {
      return prStep.value
    }
    function completed() {
      return prStep.value === numindstep.value
    }

    function getColorTutorial() {
      return completed() ? 'bg-green-5' : 'bg-primary'
    }

    function getColor() {
      if (numStepCompleted()) {
        return 'positive'
      } else {
        return 'primary'
      }
    }

    function mounted() {

      if (circuitStore.SonoDentroAdAlmeno1CircuitoConFido())
        arrStep.value.push({ ...stepCircItalia, indstep: numindstep.value })

      // arrStep.value.push({ ...stepFine, indstep: numindstep.value })

      if (userStore.isUserOk()) {
        updatestart()
      }

    }

    function isAskedToCircuit(): boolean {
      return !!(mycircuit.value && ((!userStore.IsMyCircuitByName(mycircuit.value.name) && !userStore.IsAskedCircuitByName(mycircuit.value.name))))
    }

    function isAskedToCircuitItalia(): boolean {
      return !!(circuititalia.value && ((!userStore.IsMyCircuitByName(circuititalia.value.name) && !userStore.IsAskedCircuitByName(circuititalia.value.name))))
    }

    function isSalta(step: number) {
      return (step === STEP_CIRCUIT && (mycircuit.value && isAskedToCircuit())) ||
        (step === STEP_CIRCUIT_ITALIA && (circuititalia.value && isAskedToCircuitItalia()))
    }

    function askToConfirmSkip(mystep: number) {
      if (mystep === STEP_CIRCUIT) {
        return $q.dialog({
          message: t('circuit.skipentercircuit'),
          html: true,
          ok: {
            label: t('dialog.yes'),
            push: false,
          },
          title: '',
          cancel: true,
          persistent: false,
        }).onOk(() => {
          if ((step.value === STEP_CIRCUIT)) {
            userStore.savenoCircuit(isAskedToCircuit())
          }
          indstep.value++
          return true
        }).onCancel(() => {
          return false
        })
      } else if (mystep === STEP_CIRCUIT_ITALIA) {
        askToConfirmSkipItalia(mystep)
      }
    }

    function askToConfirmSkipItalia(mystep: number) {
      return $q.dialog({
        message: t('circuit.skipentercircuit_italia'),
        html: true,
        ok: {
          label: t('dialog.yes'),
          push: false,
        },
        title: '',
        cancel: true,
        persistent: false,
      }).onOk(() => {
        if ((mystep === STEP_CIRCUIT_ITALIA)) {
          userStore.savenoCircIta(isAskedToCircuitItalia())
        }
        indstep.value++
        return true
      }).onCancel(() => {
        return false
      })
    }

    function getColorDone(indstep: number) {
      return arrStep.value[indstep].checkOkReal() ? 'positive' : 'negative'
    }

    onMounted(mounted)

    return {
      contact,
      costanti,
      checkifDisabled,
      getImgUser,
      naviga,
      setCmd,
      shared_consts,
      tools,
      showsendCoinTo,
      showAccountInfo,
      indstep,
      step,
      numindstep,
      progressLabel,
      progressStep,
      arrStep,
      strProv,
      mycircuit,
      mylistcircuits,
      userStore,
      clickFinish,
      isNextDisable,
      mycards,
      filtroutente,
      getColor,
      stepTut,
      completed,
      getColorTutorial,
      getFirstStepToFill,
      STEP_CIRCUIT,
      STEP_CIRCUIT_ITALIA,
      STEP_CITY,
      STEP_FOTO,
      STEP_NAME_SURNAME,
      isSalta,
      askToConfirmSkip,
      getColorDone,
      nascondiavviso,
      circuitsel,
      card,
      askToConfirmSkipItalia,
      circuititalia,
      usersList,
      userstoverify,
      numStepCompleted,
      globalStore,
      prStep,
      showBanner_utenti_verif,
    }
  },
})
