<template>
	<div :class="['sidebar', { collapsed }]">
		<div class="top-bar">
			<div class="brand" v-if="!collapsed">
				<img :src="logo" class="w-full" alt="logo" />
			</div>
			<div class="top-icons" :style="{
				flexDirection: collapsed ? 'column' : 'row',
				width: collapsed ? '100%' : 'auto'
			}">
				<el-dropdown placement="bottom-start" trigger="click">
					<span style="cursor: pointer">
						<SvgIcon name="Plus" />
					</span>
					<template #dropdown>
						<el-dropdown-menu>
							<el-dropdown-item @click="createWorkflow">
								{{ t('sidebar.createWorkflow') }}
							</el-dropdown-item>
							<el-dropdown-item @click="createCertificate">
								{{ t('sidebar.createCertificate') }}
							</el-dropdown-item>
						</el-dropdown-menu>
					</template>
				</el-dropdown>
				<el-tooltip placement="bottom">
					<template #content>
						<div class="tooltip-keys">
							<kbd>Ctrl</kbd>
							<span class="plus">+</span>
							<kbd>K</kbd>
							<span class="desc">{{ t('sidebar.shortcuts.quickSearch') }}</span>
						</div>
					</template>
					<span style="cursor: pointer" @click="showSearchDialog = true">
						<SvgIcon name="Search" />
					</span>
				</el-tooltip>
				<el-tooltip placement="bottom">
					<template #content>
						<div class="tooltip-keys">
							<kbd>Ctrl</kbd>
							<span class="plus">+</span>
							<kbd>B</kbd>
							<span class="desc">{{ t('sidebar.shortcuts.toggleSidebar') }}</span>
						</div>
					</template>
					<span style="cursor: pointer" @click="toggle">
						<SvgIcon name="Fold" />
					</span>
				</el-tooltip>
				<el-tooltip placement="bottom">
					<template #content>
						<span>
							{{ isDarkMode ? t('sidebar.theme.switchToLight') : t('sidebar.theme.switchToDark') }}
						</span>
					</template>
					<span style="cursor: pointer" @click="toggleTheme">
						<SvgIcon :name="isDarkMode ? 'sun' : 'moon'" />
					</span>
				</el-tooltip>
			</div>
		</div>

		<el-menu :default-active="activeMenu" router class="el-menu-vertical-demo main-menu">
			<el-menu-item v-for="item in sidebarMainMenu" :key="item.path" :index="item.path">
				<el-tooltip v-if="collapsed" :content="item.label" placement="right">
					<span>
						<SvgIcon :name="item.icon" />
					</span>
				</el-tooltip>
				<SvgIcon v-else :name="item.icon" />
				<span v-if="!collapsed" class="label">
					{{ item.label }}
					<small v-if="item.badge" class="beta">{{ item.badge }}</small>
				</span>
			</el-menu-item>
		</el-menu>

		<div class="spacer"></div>

		<div class="bottom-menu">
			<div
				v-for="item in sidebarBottomMenu"
				:key="getBottomMenuKey(item)"
				class="bottom-item"
				:class="{ active: isBottomMenuItemActive(item) }"
				@click="handleBottomMenuClick($event, item)"
			>
				<el-tooltip v-if="collapsed" :content="item.label" placement="right">
					<span>
						<SvgIcon :name="item.icon" />
					</span>
				</el-tooltip>
				<SvgIcon v-else :name="item.icon" />
				<span v-if="!collapsed" class="label">{{ item.label }}</span>
				<SvgIcon v-if="!collapsed && item.type === 'action' && item.showChevron" name="chevron-right" />
			</div>
		</div>
	</div>

	<!-- 搜索对话框 -->
	<SearchDialog :is-open="showSearchDialog" @close="showSearchDialog = false" @select="handleSearchSelect" />

	<!-- 模板弹窗 -->
	<TemplateModal :visible="showTemplateModal" @close="showTemplateModal = false" @select="handleTemplateSelect" />
	<!-- 新建工作流弹窗 -->
	<CreateWorkflowModal :visible="createModalVisible" @close="createModalVisible = false"
		@success="handleCreateSuccess" />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useI18n } from '@/composables/useI18n'
import { applyTheme } from '@/theme'
import { getSidebarBottomMenu, getSidebarMainMenu, type SidebarBottomMenuItem } from '@/config/menu'

import logo from '@/assets/logo.svg'

const SearchDialog = defineAsyncComponent(() => import('../SearchDialog/index.vue'))
const TemplateModal = defineAsyncComponent(() => import('../TemplateModal/index.vue'))
const CreateWorkflowModal = defineAsyncComponent(() => import('@/features/createModal/index.vue'))

const emit = defineEmits<{
	'settings-menu-toggle': [position: { top: number; left: number }, name: string]
}>()

const router = useRouter()
const { t, locale } = useI18n()
const collapsed = ref(false)
const showSearchDialog = ref(false)
const showTemplateModal = ref(false)
const isDarkMode = ref(false)
const createModalVisible = ref(false)

const sidebarMainMenu = computed(() => {
	locale.value
	return getSidebarMainMenu(t)
})

const sidebarBottomMenu = computed(() => {
	locale.value
	return getSidebarBottomMenu(t)
})

// 计算当前活跃的菜单项
const activeMenu = computed(() => router.currentRoute.value.path)

const isBottomMenuActive = (path: string) => router.currentRoute.value.path === path

const getBottomMenuKey = (item: SidebarBottomMenuItem) => {
	if (item.type === 'route') return item.path
	return item.activeKey || item.settingsName || item.action
}

const isBottomMenuItemActive = (item: SidebarBottomMenuItem) => {
	if (item.type === 'route') return isBottomMenuActive(item.path)
	if (item.action === 'template') return showTemplateModal.value
	return false
}

const toggle = () => {
	collapsed.value = !collapsed.value
}

const createWorkflow = () => {
	createModalVisible.value = true
}

const handleCreateSuccess = (id: string) => {
	createModalVisible.value = false
	window.open(`#/workflow/${id}`, '_blank')
}

const createCertificate = () => {
	// TODO: 实现凭证创建功能
	ElMessage.info(t('sidebar.certificateComingSoon'))
}

const handleTemplateClick = () => {
	showTemplateModal.value = true
}

const handleTemplateSelect = (templateId: string) => {
	// 导航到模板详情页面
	router.push(`/templates/${templateId}`)
	showTemplateModal.value = false
}

const handleBottomMenuClick = (event: MouseEvent, item: SidebarBottomMenuItem) => {
	if (item.type === 'route') {
		router.push(item.path)
		return
	}

	if (item.action === 'template') {
		handleTemplateClick()
		return
	}

	handleSettingsClick(event, item.settingsName || 'settings')
}

const handleKeyDown = (e: KeyboardEvent) => {
	if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
		e.preventDefault()
		showSearchDialog.value = true
	}
	if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
		e.preventDefault()
		toggle()
	}
}

onMounted(() => {
	window.addEventListener('keydown', handleKeyDown)
	// 初始化主题
	const savedMode = localStorage.getItem('app-theme-mode') || 'light'
	isDarkMode.value = savedMode === 'dark'
})

onUnmounted(() => {
	window.removeEventListener('keydown', handleKeyDown)
})

const handleSearchSelect = (item: any) => {
	console.log('Selected:', item)
}

const handleSettingsClick = (event: MouseEvent, name: string) => {
	const element = event.currentTarget as HTMLElement
	const rect = element.getBoundingClientRect()

	emit(
		'settings-menu-toggle',
		{
			top: rect.top,
			left: rect.right + 8
		},
		name
	)
}

const toggleTheme = () => {
	isDarkMode.value = !isDarkMode.value
	applyTheme(isDarkMode.value ? 'dark' : 'light')
}
</script>

<style lang="less" scoped>
* {
	color: var(--text-secondary);
}

.sidebar {
	width: 200px;
	height: 100%;
	background: var(--bg-base);
	border-right: 1px solid var(--border-light);
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	transition: width 0.18s ease;
	overflow: hidden;
}

.sidebar.collapsed {
	width: 41px;
}

.top-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 8px 10px;
	border-bottom: 1px solid var(--border-light);
}

.brand {
	display: flex;
	justify-content: center;
	align-items: center;
}

.top-icons {
	display: flex;
	gap: 10px;
	align-items: center;
}

.top-icons svg {
	cursor: pointer;
	padding: 6px 8px;
	margin: -6px -8px;
	border-radius: 4px;
	transition: all 0.2s ease;
}

.top-icons svg:hover {
	color: #810042;
	background-color: var(--bg-container);
}

.top-icons>span {
	display: flex;
	align-items: center;
	justify-content: center;
}

.top-icons>span svg {
	padding: 6px 8px;
	margin: -6px -8px;
	border-radius: 4px;
	transition: all 0.2s ease;
}

.top-icons>span:hover svg {
	color: #810042;
	background-color: var(--bg-container);
}

.main-menu {
	padding-top: 8px;
	border-right: none;
}

.el-menu-vertical-demo .el-menu-item {
	display: flex;
	align-items: center;
	gap: 10px;
	padding: 0 16px;
	height: 32px;
}

.el-menu-vertical-demo .el-menu-item:hover {
	background: var(--bg-container);
}

.el-menu-vertical-demo .el-menu-item.is-active {
	background: var(--bg-container) !important;
	color: var(--el-color-primary) !important;
	border-right: 3px solid var(--el-color-primary);
}

.label {
	font-size: 13px;
	flex: 1;
}

.beta {
	font-size: 10px;
	color: var(--text-tertiary);
	margin-left: 6px;
}

.spacer {
	flex: 1 1 auto;
}

.bottom-menu {
	padding-bottom: 8px;
	border-top: 1px solid var(--border-light);
	display: flex;
	flex-direction: column;
	gap: 6px;
}

.bottom-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 10px;
	padding: 8px 18px;
	padding-right: 10px;
	color: var(--text-primary);
	cursor: pointer;
	border-radius: 4px;
	transition: all 0.2s ease;
}

.bottom-item:hover {
	background: var(--bg-container);
	color: #810042;
}

.bottom-item.active {
	background: var(--bg-container);
	color: #810042;
}

.settings-menu-panel {
	position: absolute;
	left: 100%;
	width: 240px;
	background: var(--bg-container);
	border: 1px solid var(--border-light);
	border-radius: 4px;
	box-shadow: var(--shadow-lg);
	overflow-y: auto;

	.settings-menu-item {
		padding: 10px 16px;
		color: var(--text-secondary);
		cursor: pointer;
		transition: all 0.2s;
		font-size: 13px;
		white-space: nowrap;

		&:hover {
			background: var(--bg-base);
			color: var(--text-primary);
		}

		&.logout {
			color: #810042;
			border-top: 1px solid var(--border-light);
			margin-top: 4px;
			padding-top: 12px;

			&:hover {
				background: rgba(255, 107, 107, 0.1);
			}
		}
	}
}

.sidebar.collapsed .label {
	display: none;
}

.sidebar.collapsed .el-menu-vertical-demo .el-menu-item,
.sidebar.collapsed .bottom-item {
	justify-content: center;
	padding-left: 0;
	padding-right: 0;
}

.sidebar.collapsed .top-icons {
	gap: 10px;
	flex-direction: column;
}

.sidebar.collapsed .top-icons>span {
	width: 100%;
	justify-content: center;
}

:deep(.el-button + .el-button) {
	margin-left: 0;
}

.tooltip-keys {
	display: flex;
	align-items: center;
	gap: 4px;
	font-size: 11px;

	kbd {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		padding: 1px 4px;
		min-width: 18px;
		height: 18px;
		background: var(--bg-container);
		color: var(--text-primary);
		border: 1px solid var(--border-base);
		border-radius: 2px;
		font-family: 'Monaco', 'Courier New', monospace;
		font-weight: 500;
		font-size: 10px;
		box-shadow: var(--shadow-sm);
	}

	.plus {
		color: var(--text-tertiary);
		margin: 0 1px;
		font-size: 10px;
	}

	.desc {
		color: var(--text-placeholder);
		margin-left: 2px;
		font-size: 11px;
	}
}

:deep(.el-menu-item *) {
	vertical-align: initial;
}
</style>
