<script setup>
import { toast } from 'bulma-toast'


const router = useRouter()
const url = useRequestURL()
const tabs = useTabs()
const activeMenu = useActiveMenu()
const activeSubMenu = useActiveSubMenu()
const activeSubChildMenu = useActiveSubChildMenu()
const activeSave = useActiveSave()
const sideBarScroll = useSideBarScroll()

onMounted(() => {
  const getTabs = localStorage.getItem('tabs')
  if(getTabs) {
    tabs.value = JSON.parse(getTabs)
    if(url.pathname) {
      tabs.value.map((item, ind) => {
        if((url.pathname.startsWith(item.link) && item.link != '/') || url.pathname == item.link) {
          item.active = true
        } else {
          item.active = false
        }
        return item
      })
      router.push(url.pathname)
      activeMenu.value = ''
      activeSubMenu.value = ''
      activeSubChildMenu.value = ''
      sideBarScroll.value = 0
    }
  }
})

const openTab = (menu) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    tabs.value.map(item => {
      item.active = false
      return item
    })
    if(tabs.value.filter(i => i.link === menu.link).length >= 1) {
      const tabIndex = tabs.value.findIndex(i => i.link === menu.link)
      tabs.value[tabIndex].active = true
      localStorage.setItem('tabs', JSON.stringify(tabs.value))
      router.push(menu.link)
    } else {
      tabs.value.push({link: menu.link, text: menu.text, active: true})
      localStorage.setItem('tabs', JSON.stringify(tabs.value))
      router.push(menu.link)
    }
    activeMenu.value = ''
    activeSubMenu.value = ''
    activeSubChildMenu.value = ''
    sideBarScroll.value = 0
  }
}

const closeTab = (active, index) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    if(active) {
      tabs.value.splice(index, 1)
      tabs.value.map((item, ind) => {
        if((Number(index) - 1) === Number(ind)) {
          item.active = true
        } else {
          item.active = false
        }
        return item
      })
      localStorage.setItem('tabs', JSON.stringify(tabs.value))
      const newLink = tabs.value.filter(i => i.active)
      if(newLink.length >= 1) {
        router.push(newLink[0].link)
        activeMenu.value = ''
        activeSubMenu.value = ''
        activeSubChildMenu.value = ''
        sideBarScroll.value = 0
      }
    } else {
      tabs.value.splice(index, 1)
      localStorage.setItem('tabs', JSON.stringify(tabs.value))
    }
  }
}

const contextMenu = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const contextMenuTab = ref({})
const contextMenuIndex = ref(0)
const contextMenuHandler = (e, tab, index) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    contextMenuX.value = e.pageX
    contextMenuY.value = e.pageY
    contextMenu.value = true
    contextMenuTab.value = tab
    contextMenuIndex.value = index
  }
}

const contextMenuCloseTab = () => {
  contextMenu.value = false
  closeTab(contextMenuTab.value?.active || false, contextMenuIndex.value)
}

const contextMenuCloseAll = () => {
  tabs.value = [{link: '/', text: 'Home', active: true}]
  localStorage.setItem('tabs', JSON.stringify(tabs.value))
  contextMenu.value = false
  contextMenuTab.value = {}
  contextMenuIndex.value = 0
  router.push('/')
  activeMenu.value = ''
  activeSubMenu.value = ''
  activeSubChildMenu.value = ''
  sideBarScroll.value = 0
}

const contextMenuCloseInactive = () => {
  tabs.value = tabs.value.filter(i => i.active === true || i.link === '/');
  localStorage.setItem('tabs', JSON.stringify(tabs.value))
  contextMenu.value = false
  contextMenuTab.value = {}
  contextMenuIndex.value = 0
  activeMenu.value = ''
  activeSubMenu.value = ''
  activeSubChildMenu.value = ''
  sideBarScroll.value = 0
}

const contextMenuCloseOpen = () => {
  openTab(contextMenuTab.value)
  contextMenuCloseInactive()
}
</script>

<template>
  <div class="bg-hexfff overflowX-auto">
    <div class="tabs is-boxed">
      <ul class="px-1.5rem">
        <li v-for="(tab, index) in tabs" :id="index" :class="{'is-active': tab.active}">
          <a @click="openTab(tab)" @contextmenu.prevent="contextMenuHandler($event, tab, index)">
            <span :class="{'fg-hex999': !tab.active}">{{ tab.text }}</span>
            <button v-if="tab.link !== '/'" class="delete ml-2" @click.stop="closeTab(tab.active, index)"></button>
            <i v-else class="menu-icon tf-icons ti ti-square-rounded-chevron-down-filled fg-hex999 ml-2"></i>
          </a>
        </li>
      </ul>
    </div>
  </div>
  <teleport to="body">
    <div v-if="contextMenu" class="contextMenu" @click.self="contextMenu = false">
      <div class="contextMenuContent" :style="{left: contextMenuX + 'px', top: contextMenuY + 'px'}">
        <div v-if="Number(contextMenuIndex) !== 0" class="contextMenuItem" @click="contextMenuCloseTab">Close Tab</div>
        <div class="contextMenuItem" @click="contextMenuCloseAll">Close All Tabs</div>
        <div class="contextMenuItem" @click="contextMenuCloseInactive">Close All Inactive Tabs</div>
        <div class="contextMenuItem" @click="contextMenuCloseOpen">Open &amp; Close Other Tabs</div>
      </div>
    </div>
  </teleport>
</template>

<style scoped>
.item:not(.active) {
  color: inherit;
}
@use contextMenu;
</style>