import { computed, defineComponent, onMounted, ref, watch } from 'vue'

import type { INotif } from '@model';
import {
  IChat,
  IMessage, IMsgUsers
} from '@model'

import { date } from 'quasar'

import { tools } from '@src/store/Modules/tools'

import { useRouter } from 'vue-router'
import MixinUsers from '../../../mixins/mixin-users'
import { useNotifStore } from '@store/NotifStore'
import { useUserStore } from '@store/UserStore'

import { CTitleBanner } from '@src/components/CTitleBanner'
import { CMyFieldRec } from '@src/components/CMyFieldRec'
import { CTimeAgo } from '@src/components/CTimeAgo'
import { CMyFieldDb } from '@src/components/CMyFieldDb'
import { CMyCircuits } from '@src/components/CMyCircuits'
import { CFinder } from '@src/components/CFinder'
import { shared_consts } from '@src/common/shared_vuejs'
import { useI18n } from 'vue-i18n'
import { useQuasar } from 'quasar'
import { costanti } from '@costanti'
import { toolsext } from '@store/Modules/toolsext'
import { useGlobalStore } from '@store/globalStore'

export default defineComponent({
  name: 'coinsPopover',
  components: { CTitleBanner, CMyFieldRec, CTimeAgo, CMyFieldDb, CMyCircuits, CFinder },
  emits: ['update:modelValue'],
  props: {
    modelValue: {
      required: true,
      type: [String, Number, Boolean],
    }
  },

  setup(props, { emit }) {
    const $router = useRouter()
    const userStore = useUserStore()
    const notifStore = useNotifStore()
    const globalStore = useGlobalStore()

    const { t } = useI18n()
    const q = useQuasar()

    const loading = ref(false)

    const myuser = ref({})
    const filter = ref(costanti.MY_CIRCUITS)

    const show_all = ref(true)
    const username = computed(() => userStore.my.username)

    const getlasts_coins = computed(() => notifStore.getlasts_coins().filter((rec) => show_all.value ? true : !rec.read))
    const num_notifs_unread = computed(() => notifStore.getnumCoinsUnread())

    const notifsel = ref(<INotif>{
      dest: '',
      datenotif: new Date()
    })

    const open = computed({
      get() {
        return props.modelValue
      },

      set(value) {
        return emit('update:modelValue', value)
      }
    })

    const { getnumCoinsUnread, Username, getNumNotif, getUsernameChatByNotif, getImgByNotif, getNotifText, getTypeDirNotif, getTypeIdNotif } = MixinUsers()

    watch(() => open.value, (newval: any, oldval: any) => {
      if (getnumCoinsUnread()) {
        if (open.value)
          notifStore.setAllRead(Username(), shared_consts.QualiNotifs.CIRCUITS)
      }
    })


    // function getlasts_coins (state: IUserState) => IMessage[] {
    //
    // }

    watch(() => userStore.my.username, async (to: any, from: any) => {
      if (userStore.my.username) {
        await refreshdata(userStore.my.username)
      }
    })

    watch(() => notifStore.updateNotification, async (to: any, from: any) => {
      if (notifStore.updateNotification) {
        await refreshdata(userStore.my.username)
      }
    })

    function clickNotif(notif: INotif) {
      if (notif.openUrl) {
        const mylink = tools.updateQueryStringParameter(notif.openUrl, 'idnotif', notif._id)
        console.log('mylink', mylink, notif._id)
        if (mylink) {
          $router.replace(mylink)
        }
      }
    }

    function getlastnotifcoins(username: string): any {
      // Get msg for this chat
      if (notifStore.last_notifcoins) {
        if (userStore.isAdmin) {
          console.log('userStore.isAdmin', userStore.isAdmin, notifStore.last_notifcoins)
          return notifStore.last_notifcoins
        } else {
          return notifStore.last_notifcoins.find((rec: INotif) => rec.dest === username)
        }

      }
      // return users_msg_saved[username]
    }

    function getlastdataread(username: string): any {
      // Get msg for this

      const myrec = getlastnotifcoins(username)
      const lastdata: any = (myrec && myrec.lastdataread) ? myrec.lastdataread : tools.getLastDateReadReset()

      let mydate = ''
      if (!tools.isIsoDate(lastdata))
        mydate = lastdata.toISOString()
      else
        return lastdata

      // console.log('getlastdataread', mydate)
      return mydate
    }


    async function refreshdata(username: string) {
      try {

        if (username) {
          notifsel.value.dest = ''
          // console.log('refreshdata')
          loading.value = true

          return notifStore.updateNotifDataFromServer({
            username,
            lastdataread: getlastdataread(username),
          }).then((ris) => {

            notifStore.updateNotification = false
            notifsel.value.dest = username
            loading.value = false

            const element = document.getElementById('last')
            tools.scrollToElement(element)

            // changemsgs('', '')

          }).catch((err) => {
            console.error('   refreshdata', err)
            loading.value = false
          })
        }
      } catch (e) {
        console.error('   refreshdata', e)
        loading.value = false
      }
    }

    async function mounted() {
      myuser.value = userStore.my
      await refreshdata(userStore.my.username)
    }

    onMounted(mounted)

    return {
      getlasts_coins,
      num_notifs_unread,
      clickNotif,
      getnumCoinsUnread,
      getNumNotif,
      getUsernameChatByNotif,
      getImgByNotif,
      getNotifText,
      getTypeDirNotif,
      getTypeIdNotif,
      tools,
      shared_consts,
      myuser,
      costanti,
      toolsext,
      open,
      notifStore,
      show_all,
      t,
      username,
      userStore,
      q,
      filter,
    }
  },
})
