<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { toast } from 'vue-sonner'

import {
  Sidebar,
  SidebarContent,
  SidebarMenu,
  SidebarTrigger,
  SidebarMenuItem,
  SidebarMenuButton,
  useSidebar,
} from '@/components/ui/sidebar'
import { TooltipWrapper } from '@/components/ui/tooltip'
import { useNavigation } from '@/composables/useNavigation'
import { useSidebarAutoCollapse } from '@/composables/useSidebarAutoCollapse'
import { useReloadTraces } from '@/composables/useTraces'
import PasteNewTrace from '@/layout/sidebar/PasteNewTrace.vue'
import DataikuLogo from '@/layout/sidebar/DataikuLogo.vue'
import UserMenu from '@/layout/sidebar/UserMenu.vue'
import { WT1iser } from '@/services/wt1'

const route = useRoute()
const { open } = useSidebar()
const { backToTraces } = useNavigation()
const { mutate: reloadTraces, isPending: isReloading } = useReloadTraces()

const clickCount = ref(0)
const isFlipped = ref(false)

const isTraceListRoute = computed(() => route.name === 'traceList')
const isTraceRoute = computed(() => route.name === 'trace' || route.name === 'node')

// auto-collapse sidebar on trace navigation
useSidebarAutoCollapse()

function handleTitleClick() {
  if (isFlipped.value) return
  clickCount.value++
  if (clickCount.value >= 5) {
    isFlipped.value = true
  }
}

function handleReload() {
  reloadTraces(undefined, {
    onSuccess: () => {
      WT1iser.reloadTraces()
      toast.success('Dataset traces reloaded')
    },
    onError: (err: Error) => {
      toast.error('Failed to reload traces', {
        description: err.message || 'An unexpected error occurred',
      })
    },
  })
}
</script>

<template>
  <Sidebar collapsible="icon">
    <SidebarContent class="overflow-x-hidden">
      <div
        class="min-h-[60.5px] border-b group-data-[collapsible=icon]:border-transparent items-center flex justify-between px-4 group-data-[collapsible=icon]:px-2"
      >
        <div class="flex items-center gap-2.5 group-data-[collapsible=icon]:hidden">
          <div class="logo-flip-container h-7 w-7" @click="handleTitleClick">
            <div class="logo-flip-inner h-7 w-7 relative" :class="{ flipped: isFlipped }">
              <div class="logo-flip-front">
                <DataikuLogo class="h-7 w-7" />
              </div>
              <div class="logo-flip-back">
                <i class="dku-icon-diamond-24 text-pink-400" />
              </div>
            </div>
          </div>
          <span
            class="font-semibold text-lg text-foreground/90 tracking-tight cursor-pointer select-none line-clamp-1"
            @click="backToTraces"
          >
            Trace Explorer
          </span>
        </div>
        <TooltipWrapper content="Toggle sidebar" side="right">
          <SidebarTrigger class="text-foreground" />
        </TooltipWrapper>
      </div>

      <div class="p-2 py-3">
        <SidebarMenu>
          <SidebarMenuItem>
            <PasteNewTrace>
              <SidebarMenuButton tooltip="Paste a new trace">
                <i class="dku-icon-plus-16" />
                <span>Paste a new trace</span>
              </SidebarMenuButton>
            </PasteNewTrace>
          </SidebarMenuItem>
          <SidebarMenuItem v-if="isTraceRoute && open">
            <SidebarMenuButton tooltip="Back to traces" @click="backToTraces">
              <i class="dku-icon-arrow-left-16" />
              <span>Back to traces</span>
            </SidebarMenuButton>
          </SidebarMenuItem>
          <SidebarMenuItem v-if="isTraceListRoute && open">
            <SidebarMenuButton
              tooltip="Reload traces"
              :disabled="isReloading"
              @click="handleReload"
            >
              <i class="dku-icon-arrow-clockwise-16" :class="{ 'animate-spin': isReloading }" />
              <span>Reload traces</span>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </div>

      <RouterView name="sidebarContent" />

      <div class="p-2 border-t group-data-[collapsible=icon]:border-transparent mt-auto">
        <SidebarMenu>
          <SidebarMenuItem>
            <UserMenu />
          </SidebarMenuItem>
        </SidebarMenu>
      </div>
    </SidebarContent>
  </Sidebar>
</template>
