<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useConnectionsStore } from '../stores/connections'
import { useSftpTabsStore } from '../stores/sftpTabs'
import { useTerminalTabsStore } from '../stores/terminalTabs'
import TerminalWorkspaceView from '../views/TerminalWorkspaceView.vue'
import { ArrowLeftRight, Server, LogOut, Menu, X, Terminal, FolderOpen, MonitorCog, Clock3 } from 'lucide-vue-next'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const connectionsStore = useConnectionsStore()
const sftpTabsStore = useSftpTabsStore()
const tabsStore = useTerminalTabsStore()

const sidebarOpen = ref(false)
const now = ref(new Date())
let clockTimer = 0

const terminalTabs = computed(() => tabsStore.tabs)
const sftpTabs = computed(() => sftpTabsStore.tabs)
const showTerminalWorkspace = computed(() => route.path === '/terminal')
const keepTerminalWorkspaceMounted = computed(() => showTerminalWorkspace.value || terminalTabs.value.length > 0)

const currentSectionTitle = computed(() => {
  if (route.path.startsWith('/connections')) return 'Session Manager'
  if (route.path.startsWith('/terminal')) return 'Terminal Workspace'
  if (route.path.startsWith('/sftp/')) return 'SFTP Browser'
  if (route.path.startsWith('/transfers')) return 'Transfer Queue'
  return 'SSH Manager'
})

const nowText = computed(() => {
  return now.value.toLocaleTimeString([], {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
})

function closeSidebar() {
  sidebarOpen.value = false
}

function handleTabClick(tabId: string) {
  tabsStore.activate(tabId)
  router.push('/terminal')
  closeSidebar()
}

function handleTabClose(tabId: string, event: Event) {
  event.stopPropagation()
  tabsStore.close(tabId)
}

function isCurrentSftpRoute(connectionId: number) {
  if (route.name !== 'Sftp') return false

  const routeParamId = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id
  return Number(routeParamId) === connectionId
}

function handleSftpTabClick(tabId: string, connectionId: number) {
  sftpTabsStore.activate(tabId)
  router.push(`/sftp/${connectionId}`)
  closeSidebar()
}

function handleSftpTabClose(tabId: string, connectionId: number, event: Event) {
  event.stopPropagation()

  const shouldNavigate = isCurrentSftpRoute(connectionId)
  sftpTabsStore.close(tabId)

  if (!shouldNavigate) return

  if (sftpTabsStore.activeTab) {
    router.push(`/sftp/${sftpTabsStore.activeTab.connectionId}`)
    return
  }

  router.push('/connections')
}

function handleLogout() {
  authStore.logout()
  router.push('/login')
}

onMounted(() => {
  connectionsStore.fetchConnections().catch(() => {})
  clockTimer = window.setInterval(() => {
    now.value = new Date()
  }, 1000)
})

onUnmounted(() => {
  clearInterval(clockTimer)
})
</script>

<template>
  <div class="flex h-screen bg-slate-950 text-slate-100">
    <button
      @click="sidebarOpen = !sidebarOpen"
      class="lg:hidden fixed top-3 left-3 z-40 p-2 rounded-md bg-slate-800 border border-slate-600 text-slate-200 hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-cyan-400 cursor-pointer"
      aria-label="切换侧边栏"
    >
      <Menu v-if="!sidebarOpen" class="w-5 h-5" aria-hidden="true" />
      <X v-else class="w-5 h-5" aria-hidden="true" />
    </button>

    <aside
      :class="[
        'w-72 border-r border-slate-700/80 flex flex-col transition-transform duration-200 z-30 bg-slate-900/95 backdrop-blur-sm',
        'fixed lg:static inset-y-0 left-0',
        sidebarOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
      ]"
    >
      <div class="px-4 py-3 border-b border-slate-700/80">
        <div class="flex items-center gap-3">
          <div class="w-9 h-9 rounded-md bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center">
            <MonitorCog class="w-5 h-5 text-white" aria-hidden="true" />
          </div>
          <div>
            <h1 class="text-sm font-semibold tracking-wide text-slate-100">SSH Manager</h1>
            <p class="text-xs text-slate-400">{{ authStore.displayName || authStore.username }}</p>
          </div>
        </div>
      </div>

      <nav class="flex-1 px-3 py-3 overflow-y-auto space-y-4 pt-16 lg:pt-3">
        <div>
          <p class="px-2 text-[11px] uppercase tracking-wider text-slate-500 mb-2">工作区</p>
          <div class="space-y-1">
            <RouterLink
              to="/connections"
              @click="closeSidebar"
              class="flex items-center gap-2.5 px-3 py-2.5 rounded-md text-sm text-slate-300 hover:bg-slate-800 hover:text-slate-100 transition-colors duration-200 cursor-pointer min-h-[44px] focus:outline-none focus:ring-2 focus:ring-cyan-500"
              :class="{ 'bg-slate-800 text-cyan-300 border border-cyan-500/30': route.path === '/connections' }"
              aria-label="连接列表"
            >
              <Server class="w-4 h-4 flex-shrink-0" aria-hidden="true" />
              <span>Connections</span>
            </RouterLink>
            <RouterLink
              to="/transfers"
              @click="closeSidebar"
              class="flex items-center gap-2.5 px-3 py-2.5 rounded-md text-sm text-slate-300 hover:bg-slate-800 hover:text-slate-100 transition-colors duration-200 cursor-pointer min-h-[44px] focus:outline-none focus:ring-2 focus:ring-cyan-500"
              :class="{ 'bg-slate-800 text-cyan-300 border border-cyan-500/30': route.path === '/transfers' }"
              aria-label="传输"
            >
              <ArrowLeftRight class="w-4 h-4 flex-shrink-0" aria-hidden="true" />
              <span>Transfers</span>
            </RouterLink>
          </div>
        </div>

        <div v-if="terminalTabs.length > 0" class="pt-3 border-t border-slate-700/70">
          <div class="flex items-center justify-between px-2 mb-2">
            <p class="text-[11px] uppercase tracking-wider text-slate-500">Terminal Sessions</p>
            <span class="text-[11px] text-slate-500">{{ terminalTabs.length }}</span>
          </div>
          <div class="space-y-1">
            <div
              v-for="tab in terminalTabs"
              :key="tab.id"
              class="group flex items-center gap-2 rounded-md border border-transparent px-2 py-2 hover:bg-slate-800 transition-colors"
              :class="{ 'bg-slate-800 border-cyan-500/30': tab.active && route.path === '/terminal' }"
            >
              <button
                type="button"
                @click="handleTabClick(tab.id)"
                class="flex-1 min-w-0 text-left cursor-pointer focus:outline-none"
                :aria-label="`切换终端会话 ${tab.title}`"
              >
                <div class="flex items-center gap-2">
                  <span class="w-2 h-2 rounded-full" :class="tab.active ? 'bg-cyan-400' : 'bg-slate-600'" />
                  <Terminal class="w-3.5 h-3.5 text-slate-400" aria-hidden="true" />
                  <span class="truncate text-sm text-slate-200">{{ tab.title }}</span>
                </div>
              </button>
              <button
                type="button"
                @click="(e) => handleTabClose(tab.id, e)"
                class="p-1 rounded text-slate-500 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 hover:bg-slate-700 hover:text-slate-200 transition-opacity duration-200 cursor-pointer"
                aria-label="关闭终端标签"
              >
                <X class="w-3 h-3" aria-hidden="true" />
              </button>
            </div>
          </div>
        </div>

        <div v-if="sftpTabs.length > 0" class="pt-3 border-t border-slate-700/70">
          <div class="flex items-center justify-between px-2 mb-2">
            <p class="text-[11px] uppercase tracking-wider text-slate-500">File Sessions</p>
            <span class="text-[11px] text-slate-500">{{ sftpTabs.length }}</span>
          </div>
          <div class="space-y-1">
            <div
              v-for="tab in sftpTabs"
              :key="tab.id"
              class="group flex items-center gap-2 rounded-md border border-transparent px-2 py-2 hover:bg-slate-800 transition-colors"
              :class="{ 'bg-slate-800 border-cyan-500/30': tab.active && route.path === `/sftp/${tab.connectionId}` }"
            >
              <button
                type="button"
                @click="handleSftpTabClick(tab.id, tab.connectionId)"
                class="flex-1 min-w-0 text-left cursor-pointer focus:outline-none"
                :aria-label="`切换文件会话 ${tab.title}`"
              >
                <div class="flex items-center gap-2">
                  <span class="w-2 h-2 rounded-full" :class="tab.active ? 'bg-emerald-400' : 'bg-slate-600'" />
                  <FolderOpen class="w-3.5 h-3.5 text-slate-400" aria-hidden="true" />
                  <span class="truncate text-sm text-slate-200">{{ tab.title }}</span>
                </div>
              </button>
              <button
                type="button"
                @click="(e) => handleSftpTabClose(tab.id, tab.connectionId, e)"
                class="p-1 rounded text-slate-500 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 hover:bg-slate-700 hover:text-slate-200 transition-opacity duration-200 cursor-pointer"
                aria-label="关闭文件标签"
              >
                <X class="w-3 h-3" aria-hidden="true" />
              </button>
            </div>
          </div>
        </div>
      </nav>

      <div class="p-3 border-t border-slate-700/80">
        <button
          @click="handleLogout"
          class="flex items-center gap-2.5 px-3 py-2.5 rounded-md text-sm text-slate-300 hover:bg-slate-800 hover:text-slate-100 transition-colors duration-200 cursor-pointer w-full min-h-[44px] focus:outline-none focus:ring-2 focus:ring-cyan-500"
          aria-label="退出登录"
        >
          <LogOut class="w-4 h-4" aria-hidden="true" />
          <span>退出登录</span>
        </button>
      </div>
    </aside>

    <div
      v-if="sidebarOpen"
      class="lg:hidden fixed inset-0 bg-black/55 z-20"
      aria-hidden="true"
      @click="sidebarOpen = false"
    />

    <main class="flex-1 min-w-0 overflow-hidden flex flex-col">
      <header class="h-12 border-b border-slate-700/80 bg-slate-900/70 backdrop-blur px-4 md:px-5 flex items-center justify-between">
        <div class="flex items-center gap-3 min-w-0">
          <h2 class="text-sm md:text-base font-medium text-slate-100 truncate">{{ currentSectionTitle }}</h2>
          <div class="hidden md:flex items-center gap-2 text-xs text-slate-400">
            <span class="px-2 py-1 rounded bg-slate-800 border border-slate-700">TTY {{ terminalTabs.length }}</span>
            <span class="px-2 py-1 rounded bg-slate-800 border border-slate-700">SFTP {{ sftpTabs.length }}</span>
          </div>
        </div>
        <div class="flex items-center gap-2 text-xs text-slate-400">
          <Clock3 class="w-3.5 h-3.5" aria-hidden="true" />
          <span class="tabular-nums">{{ nowText }}</span>
        </div>
      </header>

      <div class="flex-1 min-h-0 overflow-auto">
        <div v-if="keepTerminalWorkspaceMounted" v-show="showTerminalWorkspace" class="h-full">
          <TerminalWorkspaceView :visible="showTerminalWorkspace" />
        </div>
        <RouterView v-slot="{ Component, route }">
          <template v-if="!showTerminalWorkspace">
            <keep-alive :max="10" v-if="route.meta.keepAlive">
              <component :is="Component" :key="route.params.id" />
            </keep-alive>
            <component :is="Component" :key="route.fullPath" v-else />
          </template>
        </RouterView>
      </div>
    </main>
  </div>
</template>
