<script setup>
const router = useRouter()
const tabs = useTabs()

const props = defineProps({
  params: Object
})

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const viewHandler = () => {
  //router.push(`/users/organizations/${props.params.data.id}/view`)
  openTab(`/view/organization-${props.params.data.id}`, `Organization: View Details`)
}
const duplicateHandler = () => {
  //router.push(`/users/organizations/${props.params.data.id}/duplicate`)
  openTab(`/duplicate/organization-${props.params.data.id}`, `Organization: Duplicate`)
}
const editHandler = () => {
  //router.push(`/users/organizations/${props.params.data.id}/edit`)
  openTab(`/edit/organization-${props.params.data.id}`, `Organization: ${props.params.data.name}`)
}
const deleteHandler = async () => {
  const confirmation = confirm('Are you sure want to delete this record?')
  if(confirmation) {
    await $fetch('/api/admin/organizations/'+props.params.data.id, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    location.reload()
  }
}
</script>

<template>
  <div class="d-inlineFlex items-center gap-5px">
    <span class="tf-icon ti ti-eye ti-sm me-1 fg-info cursor-pointer" @click="viewHandler"></span>
    <span class="tf-icon ti ti-copy ti-sm me-1 fg-info cursor-pointer" @click="duplicateHandler"></span>
    <span class="tf-icon ti ti-pencil ti-sm me-1 fg-warning cursor-pointer" @click="editHandler"></span>
    <span class="tf-icon ti ti-trash ti-sm me-1 fg-danger cursor-pointer" @click="deleteHandler"></span>
  </div>
</template>