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

const STEP_NAME_SURNAME = 2
const STEP_FOTO = 5
const STEP_CIRCUIT = 3

export default defineComponent({
  name: 'CMyProfileTutorial',
  components: {
    CSendCoins, CSaldo, CUserInfoAccount,
    CMySelectCity, CMyFieldRec, 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 $q = useQuasar()
    const { t } = useI18n()
    const $router = useRouter()
    const $route = useRoute()

    const showAccountInfo = ref(false)
    const step = ref(1)

    const username = ref('')
    const showsendCoinTo = ref(false)
    const mycircuit = ref(<ICircuit | undefined | null>null)

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


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

    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 strProv = computed(() => {

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

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

    watch(() => step.value, (newval: number, oldval: number) => {

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

      userStore.saveStepTutorial(step.value)
      if (step.value >= numstep.value) {
        tools.scrollToTop()
      }

      if ((step.value === STEP_CIRCUIT - 1) || (step.value === STEP_CIRCUIT )) {
        mycircuit.value = circuitStore.getCircuitByProvince(strProv.value)
        userStore.savenoCircuit(isAskedToCircuit())
      }

      if (step.value === STEP_NAME_SURNAME + 1) {
        let index = step.value
        console.log('Salva ', arrStep[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 = step.value
        if (userStore.my.profile.img) {
          // foto esistente
          userStore.savenoFoto(false)
        } else {
          userStore.savenoFoto(true)
        }
      }

    })


    const arrStep = [
      {
        step: 1,
        title: t('tutorial.step_residence_title'),
        extratitle: function () { return ': ' + contact.value!.profile.resid_province },
        label: t('tutorial.step_residence'),
        checkOk: function () { return contact.value ? !!contact.value.profile.resid_province : false },
        checkOkReal: function () { 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,
      },
      {
        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: 4,
        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_foto_title'),
        extratitle: function () { return ': (' + (userStore.my.profile.img ? t('dialog.yes') : t('dialog.no')) + ')' },
        label: t('tutorial.step_foto'),
        checkOk: function () {
          return !!userStore.my.profile.img
        },
        checkOkReal: function () { return this.checkOk() },
        icon: 'fas fa-tshirt',
        required: false,
      },
      {
        step: 6,
        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 numstep = computed(() => arrStep.length)

    const prStep = computed(() => {

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

    const progressStep = computed(() => {

      if (numstep.value > 0)
        return prStep.value / numstep.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
        }
      }

      mycircuit.value = circuitStore.getCircuitByProvince(strProv.value)

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

      userStore.my.profile.stepTutorial = getFirstStepToFill()

      step.value = userStore.my.profile.stepTutorial ? userStore.my.profile.stepTutorial : 1
      if (step.value > numstep.value)
        step.value = numstep.value

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

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


    }


    function getFirstStepToFill() {
      let num = 1
      for (const mystep of arrStep) {
        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) {
      let mystr = ''

      return mystr

    }

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

    function clickFinish() {
      userStore.my.profile.stepTutorial = numstep.value + 1
      step.value = numstep.value + 1

    }

    function isNextDisable() {
      try {
        return arrStep[step.value - 1].required && !arrStep[step.value - 1].checkOk()
      } catch (e) {
        return false
      }
    }

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

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

    function getColor() {
      if (numStepCompleted()) {
        return 'positive'
      } else {
        return 'primary'
      }
    }
    function mounted() {
      if (userStore.isUserOk()) {
        updatestart()
      }

    }

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

    function isSalta() {
      return step.value === STEP_CIRCUIT && (mycircuit.value && isAskedToCircuit())
    }

    function askToConfirmSkip() {
      return $q.dialog({
        message: t('circuit.skipentercircuit'),
        html: true,
        ok: {
          label: t('dialog.yes'),
          push: false,
        },
        title: '',
        cancel: true,
        persistent: false,
      }).onOk(() => {
        step.value++
        return true
      }).onCancel(() => {
        return false
      })
    }

    function getColorDone(step: number) {
      return arrStep[step - 1].checkOkReal() ? 'positive' : 'negative'
    }

    onMounted(mounted)

    return {
      contact,
      costanti,
      checkifDisabled,
      getImgUser,
      naviga,
      setCmd,
      shared_consts,
      tools,
      showsendCoinTo,
      showAccountInfo,
      step,
      numstep,
      progressLabel,
      progressStep,
      arrStep,
      strProv,
      mycircuit,
      userStore,
      clickFinish,
      isNextDisable,
      mycards,
      filtroutente,
      getColor,
      stepTut,
      completed,
      getColorTutorial,
      getFirstStepToFill,
      STEP_CIRCUIT,
      isSalta,
      askToConfirmSkip,
      getColorDone,
    }
  },
})
