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

export const useSidebarState = () => {
  const collapsed = ref(false)
  const hasToggle = ref(false)
  const windowWidth = ref(window.innerWidth)

  const toggleSidebar = () => {
    collapsed.value = !collapsed.value
    hasToggle.value = collapsed.value
    
    if(collapsed.value) {
      $(".side-text").addClass("text-hide");
      $(".collapse").addClass("text-hide");
      $(".hasSub").addClass("hide-after");
      
    }else{
      $(".side-text").removeClass("text-hide");
      $(".collapse").removeClass("text-hide");
      $(".hasSub").removeClass("hide-after");
    }
  }

  const handleMouseEnter = (event) => {
    if (collapsed.value) {
      $(event.currentTarget).addClass("nav-item-sub");
      var hasSubItem = $(event.currentTarget).find('.hasSub').length > 0;
      if (hasSubItem) {
        $(event.currentTarget).find(".collapse").addClass("icon-hover");
      }else{
        $(event.currentTarget).find(".side-text").addClass("icon-hover");
      }
    }
  }

  const handleMouseLeave = (event) => {
    if (collapsed.value) {
      $(event.currentTarget).removeClass("nav-item-sub");
      var hasSubItem = $(event.currentTarget).find('.hasSub').length > 0;
      if (hasSubItem) {
        $(event.currentTarget).find(".collapse").removeClass("icon-hover");
      }else{
        $(event.currentTarget).find(".side-text").removeClass("icon-hover");
      }
    }
  }

  const hoverSidebar = () => (hasToggle.value ? collapsed.value = false : null)
  const hoverOutSidebar = () => (hasToggle.value ? collapsed.value = true : null)

  const updateWindowWidth = () => {
    windowWidth.value = window.innerWidth
  }

  onMounted(() => {
    window.addEventListener('resize', updateWindowWidth)
    if (windowWidth.value <= 200) {
      toggleSidebar()
    }

    const sidebarItems = document.querySelectorAll('.side-nav .nav-item')
    sidebarItems.forEach(item => {
      item.addEventListener('mouseover', handleMouseEnter)
      item.addEventListener('mouseout', handleMouseLeave)
    })
  })

  onUnmounted(() => {
    window.removeEventListener('resize', updateWindowWidth)
  })

  watch(windowWidth, (newWidth) => {
    if (newWidth <= 1000 && !collapsed.value) {
      toggleSidebar()
    } else if (newWidth > 1000 && collapsed.value) {
      toggleSidebar()
    }
  })

  const SIDEBAR_WIDTH = 250
  const SIDEBAR_WIDTH_COLLAPSED = 70
  const sidebarWidth = computed(() => `${collapsed.value ? SIDEBAR_WIDTH_COLLAPSED : SIDEBAR_WIDTH}px`)

  return {
    collapsed,
    hasToggle,
    windowWidth,
    toggleSidebar,
    hoverSidebar,
    hoverOutSidebar,
    sidebarWidth
  }
}