import { defineComponent, onMounted, ref, watch, computed, onBeforeUnmount } from 'vue'
import { tools } from '@tools'
import { useUserStore } from '@store/UserStore'
import { useRouter } from 'vue-router'
import { useGlobalStore } from '@store/globalStore'
import { useProducts } from '@store/Products'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { costanti } from '@costanti'

import { shared_consts } from '@src/common/shared_vuejs'
import { CProductCard } from '@src/components/CProductCard'
import { CSelectUserActive } from '@src/components/CSelectUserActive'
import type { IProduct } from '@src/model'

export default defineComponent({
  name: 'ProductsList',
  components: { CProductCard, CSelectUserActive },
  props: {},
  setup() {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const productStore = useProducts()
    const router = useRouter()
    const $q = useQuasar()
    const { t } = useI18n()

    const search = ref('')

    const cosa = ref(0)
    const cat = ref('')
    const subcat = ref('')
    const idGasSel = ref('')
    const loadpage = ref(false)
    const refreshpage = ref(false)
    const show_hide = ref(false)

    const arrProducts = ref<any>([])

    const numRecLoaded = ref(0)


    // Create a ref for the component to fix
    const componentToFixRef = ref(<any>null);

    const isFixed = ref(false);

    const arrLoaded = computed(() => {
      if (arrProducts.value && numRecLoaded.value)
        return arrProducts.value.slice(0, numRecLoaded.value)
      else {
        return []
      }
    })

    // Register the scroll event on component mount
    const handleScroll = () => {
      const scrollTop = window.scrollY || document.documentElement.scrollTop;

      // Set a threshold value based on how much scroll is needed to fix the components
      const threshold = 300;

      // Update the isFixed ref based on the scroll position
      isFixed.value = scrollTop > threshold;
    };

    watch(() => cat.value, (newval, oldval) => {
      calcArrProducts()
    })

    watch(() => subcat.value, (newval, oldval) => {
      calcArrProducts()
    })

    watch(() => idGasSel.value, (newval, oldval) => {
      calcArrProducts()
    })

    watch(() => search.value, (newval, oldval) => {
      calcArrProducts()
      if (tools.scrollTop() > 300) {
        tools.scrollToTopValue(300)
      }
    })

    watch(() => cosa.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_COSA_PRODOTTI, cosa.value.toString())
      if (cosa.value !== shared_consts.PROD.TUTTI) {
        cat.value = ''
        subcat.value = ''
      }

      calcArrProducts()
    })

    function calcArrProducts() {
      // console.log('calcArrProducts')

      refreshpage.value = true
      let arrprod = productStore.getProducts(cosa.value)
      const catstr = cat.value;
      const subcatstr = subcat.value;
      let gasselstr = ''
      if (cosa.value === shared_consts.PROD.GAS) {
        gasselstr = idGasSel.value
      }
      const lowerSearchText = search.value.toLowerCase().trim();
      if ((!lowerSearchText || (lowerSearchText && lowerSearchText.length < 2)) && !catstr && !subcatstr && (!gasselstr && (cosa.value !== shared_consts.PROD.GAS))) {

      } else {

        arrprod = arrprod.filter((product: IProduct) => {
          if (product && product.productInfo && !!product.productInfo.name) {
            const lowerName = product.productInfo.name.toLowerCase();
            const hasCategoria = !catstr || (catstr && product.productInfo.idCatProds?.includes(catstr));
            const hasSubCategoria = !subcatstr || (subcatstr && product.productInfo.idSubCatProds?.includes(subcatstr));

            let productgassel = true
            if (gasselstr || (cosa.value === shared_consts.PROD.GAS)) {
              productgassel = (product.idGasordine === gasselstr)
            }

            // Use a regular expression to match whole words
            const codeMatch = new RegExp(`\\b${lowerSearchText}\\b`, 'i');
            const nameMatch = new RegExp(`\\b${lowerSearchText}`, 'i');

            // Check if any word in lowerName starts with lowerSearchText
            const anyWordStartsWithSearch = lowerName.split(/\s+/).some(word => nameMatch.test(word));

            return (codeMatch.test(product.productInfo.code) || anyWordStartsWithSearch) && hasCategoria && hasSubCategoria && productgassel;
          }
        });
      }

      arrProducts.value = arrprod
      loaddata()
      refreshpage.value = false
    }

    /*function getProducts() {
      let arrprod = productStore.getProducts(cosa.value)
      if (!search.value) {
        return arrprod
      }

      let lowerSearchText = search.value.toLowerCase();
      let catstr = cat.value;

      return arrprod.filter((product: IProduct) => {
        let lowerName = product.productInfo.name!.toLowerCase();
        const hasCategoria = !catstr || (catstr && product.productInfo.idCatProds?.includes(catstr));
        return (product.productInfo.code!.includes(search.value) || lowerName.includes(lowerSearchText)) && hasCategoria
      });
    }*/

    async function mounted() {
      loadpage.value = false
      await productStore.loadProducts(true)
      cosa.value = tools.getCookie(tools.COOK_COSA_PRODOTTI, shared_consts.PROD.GAS, true)
      if (cosa.value === shared_consts.PROD.TUTTI)
        cosa.value = shared_consts.PROD.GAS

      // Inizializza
      loadpage.value = true
      window.addEventListener('scroll', handleScroll);

      calcArrProducts()

      loaddata()
    }

    function loaddata() {
      numRecLoaded.value = 20
    }

    // Remove the event listener on component destroy
    onBeforeUnmount(() => {
      window.removeEventListener('scroll', handleScroll);
    });

    function getCatProds() {
      const arrcat = productStore.getCatProds(shared_consts.PROD.BOTTEGA)

      // console.log('getCatProds', arrcat)
      let riscat: any = []
      if (arrcat && arrcat.length > 0) {
        riscat = [{ label: 'Tutti', value: '', icon: undefined, color: undefined }]
        for (const rec of arrcat) {
          riscat.push({ label: rec.name, value: rec._id, icon: rec.icon, color: rec.color })
        }
      }

      return riscat
    }
    function getCatProdsByGas(idGasOrdine: string): any {
      const arrcat = productStore.getCatProdsByGas(idGasOrdine)
      let riscat: any = []
      if (arrcat && arrcat.length > 0) {
        riscat = [{ label: 'Tutti', value: '', icon: undefined, color: undefined }]
        for (const rec of arrcat) {
          riscat.push({ label: rec.name, value: rec._id, icon: rec.icon, color: rec.color })
        }
      }

      return riscat
    }
    function getSubCatProdsByGas(idGasOrdine: string, idCatProd: string): any {
      const arrcat = productStore.getSubCatProdsByGas(idGasOrdine, idCatProd)
      let riscat: any = []
      if (arrcat && arrcat.length > 0) {
        riscat = [{ label: 'Tutti', value: '', icon: undefined, color: undefined }]
        for (const rec of arrcat) {
          riscat.push({ label: rec.name, value: rec._id, icon: rec.icon, color: rec.color })
        }
      }

      return riscat
    }


    function onLoadScroll(index: number, done: any) {
      if (index >= 1) {
        if (numRecLoaded.value < arrProducts.value.length) {

          const step = 10
          let mynrec = numRecLoaded.value + step

          if (mynrec > arrProducts.value.length)
            mynrec = arrProducts.value.length

          numRecLoaded.value = mynrec

        }
        done()
      } else {
        done(true)
      }
    }

    onMounted(mounted)

    return {
      userStore,
      costanti,
      tools,
      toolsext,
      search,
      cosa,
      shared_consts,
      getCatProds,
      getCatProdsByGas,
      cat,
      subcat,
      idGasSel,
      productStore,
      t,
      loadpage,
      refreshpage,
      componentToFixRef,
      isFixed,
      arrProducts,
      show_hide,
      onLoadScroll,
      numRecLoaded,
      arrLoaded,
      getSubCatProdsByGas,
    }
  }
})

