<template>
	<div class="dashboard-container">
		<!-- 欢迎横幅 -->
		<div class="welcome-banner">
			<div class="welcome-content">
				<h1 style="color: #fff !important">{{ t('pages.dashboard.welcomeTitle') }}</h1>
				<p style="color: #fff !important">
					{{ t('pages.dashboard.welcomeSubtitle', { date: currentDate }) }}
				</p>
			</div>
			<el-button type="primary" size="large" @click="createWorkflow">
				<SvgIcon name="workflow" size="16" />
				{{ t('pages.dashboard.createWorkflow') }}
			</el-button>
		</div>

		<!-- 统计卡片 -->
		<div class="stats-grid">
			<div class="stat-card" @click="$router.push('/orchestration')">
				<div class="stat-icon purple">
					<SvgIcon name="workflow" size="24" />
				</div>
				<div class="stat-info">
					<div class="stat-value">{{ recentWorkflows.length }}</div>
					<div class="stat-label">{{ t('pages.dashboard.stats.workflowTotal') }}</div>
				</div>
				<div class="stat-trend up">↑ 12%</div>
			</div>
			<div class="stat-card" @click="$router.push('/execution')">
				<div class="stat-icon blue">
					<SvgIcon name="play" size="24" />
				</div>
				<div class="stat-info">
					<div class="stat-value">186</div>
					<div class="stat-label">{{ t('pages.dashboard.stats.todayExecutions') }}</div>
				</div>
				<div class="stat-trend up">↑ 8%</div>
			</div>
			<div class="stat-card">
				<div class="stat-icon green">
					<SvgIcon name="check-circle" size="24" />
				</div>
				<div class="stat-info">
					<div class="stat-value">96.8%</div>
					<div class="stat-label">{{ t('pages.dashboard.stats.successRate') }}</div>
				</div>
				<div class="stat-trend up">↑ 2%</div>
			</div>
			<div class="stat-card">
				<div class="stat-icon orange">
					<SvgIcon name="clock" size="24" />
				</div>
				<div class="stat-info">
					<div class="stat-value">2.4s</div>
					<div class="stat-label">{{ t('pages.dashboard.stats.avgResponse') }}</div>
				</div>
				<div class="stat-trend down">↓ 0.3s</div>
			</div>
		</div>

		<!-- 快速操作 -->
		<div class="quick-actions-section">
			<h2>{{ t('pages.dashboard.quickActions.title') }}</h2>
			<div class="actions-grid">
				<div class="action-card" @click="createWorkflow">
					<div class="action-icon">
						<SvgIcon name="Plus" size="28" />
					</div>
					<div class="action-title">{{ t('pages.dashboard.quickActions.newWorkflow.title') }}</div>
					<div class="action-desc">{{ t('pages.dashboard.quickActions.newWorkflow.desc') }}</div>
				</div>
				<div class="action-card" @click="useTemplate">
					<div class="action-icon">
						<SvgIcon name="box" size="28" />
					</div>
					<div class="action-title">{{ t('pages.dashboard.quickActions.useTemplate.title') }}</div>
					<div class="action-desc">{{ t('pages.dashboard.quickActions.useTemplate.desc') }}</div>
				</div>
				<div class="action-card" @click="$router.push('/log-stream')">
					<div class="action-icon">
						<SvgIcon name="log-in" size="28" />
					</div>
					<div class="action-title">{{ t('pages.dashboard.quickActions.viewLogs.title') }}</div>
					<div class="action-desc">{{ t('pages.dashboard.quickActions.viewLogs.desc') }}</div>
				</div>
				<div class="action-card" @click="$router.push('/docs')">
					<div class="action-icon">
						<SvgIcon name="book" size="28" />
					</div>
					<div class="action-title">{{ t('pages.dashboard.quickActions.viewDocs.title') }}</div>
					<div class="action-desc">{{ t('pages.dashboard.quickActions.viewDocs.desc') }}</div>
				</div>
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="main-content-grid">
			<!-- 最近工作流 -->
			<div class="content-panel">
				<div class="panel-header">
					<h3>{{ t('pages.dashboard.recentWorkflows.title') }}</h3>
					<el-button text @click="$router.push('/management')">
						{{ t('pages.dashboard.recentWorkflows.viewAll') }}
					</el-button>
				</div>
				<div class="workflow-list">
					<div class="workflow-item" v-for="item in recentWorkflows" :key="item.id" @click="toEditor(item.id)">
						<div class="workflow-icon">
							<SvgIcon name="workflow" size="20" />
						</div>
						<div class="workflow-main">
							<div class="workflow-title">{{ item.title }}</div>
							<div class="workflow-meta">{{ item.created }}</div>
						</div>
						<el-tag size="small" type="success">{{ t('common.status.active') }}</el-tag>
						<el-button text type="danger" @click.stop="deleteWorkflow(item.id)" :icon="Delete">
						</el-button>
					</div>
				</div>
			</div>

			<!-- 最近活动 -->
			<div class="content-panel">
				<div class="panel-header">
					<h3>{{ t('pages.dashboard.recentActivities.title') }}</h3>
					<el-button text @click="$router.push('/execution')">
						{{ t('pages.dashboard.recentActivities.viewAll') }}
					</el-button>
				</div>
				<div class="activity-list">
					<div class="activity-item" v-for="item in recentActivities" :key="item.id">
						<div class="activity-icon" :class="item.type">
							<SvgIcon :name="item.icon" size="16" />
						</div>
						<div class="activity-main">
							<div class="activity-text">{{ item.text }}</div>
							<div class="activity-time">{{ item.time }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 推荐模板 -->
		<div class="templates-section">
			<div class="panel-header" style="padding: 10px">
				<h2>{{ t('pages.dashboard.recommendedTemplates.title') }}</h2>
				<el-button text @click="templateModalVisible = true">
					{{ t('pages.dashboard.recommendedTemplates.viewMore') }}
				</el-button>
			</div>
			<div class="templates-grid">
				<div class="template-card" v-for="item in templates" :key="item.id" @click="goToTemplate(item.id)">
					<div class="template-icon">
						<SvgIcon :name="item.icon" size="32" />
					</div>
					<div class="template-title">{{ item.name }}</div>
					<div class="template-desc">{{ item.desc }}</div>
					<el-tag size="small">{{ item.category }}</el-tag>
				</div>
			</div>
		</div>

		<!-- 模板弹窗 -->
		<TemplateModal :visible="templateModalVisible" @close="templateModalVisible = false"
			@select="handleTemplateSelect" />

		<!-- 新建工作流弹窗 -->
		<CreateWorkflowModal :visible="createModalVisible" @close="createModalVisible = false"
			@success="handleCreateSuccess" />
	</div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import SvgIcon from '@/components/SvgIcon/index.vue'
import TemplateModal from '@/components/TemplateModal/index.vue'
import CreateWorkflowModal from '@/features/createModal/index.vue'
import { useI18n } from '@/composables/useI18n'

import { agent } from '@repo/api-service'

const $router = useRouter()
const { locale, t, tm } = useI18n()

// 当前日期
const currentDate = computed(() => {
	const now = new Date()
	const formatLocale = locale.value === 'en-us' ? 'en-US' : 'zh-CN'
	return new Intl.DateTimeFormat(formatLocale, {
		year: 'numeric',
		month: 'long',
		day: 'numeric'
	}).format(now)
})

// 模板弹窗
const templateModalVisible = ref(false)

// 新建工作流弹窗
const createModalVisible = ref(false)

// 创建工作流
const createWorkflow = () => {
	createModalVisible.value = true
}

// 前往编辑器
const toEditor = (id: string) => {
	$router.push({
		path: `/workflow/${id}`
	})
}

// 使用模板，打开弹窗
const useTemplate = () => {
	templateModalVisible.value = true
}

// 进入模板详情页面
const goToTemplate = (templateId: number) => {
	$router.push(`/templates/${templateId}`)
}

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

// 新建工作流成功回调
const handleCreateSuccess = (id: string) => {
	createModalVisible.value = false
	// $router.push(`/workflow/${id}`)
	window.open(`#/workflow/${id}`, '_blank')
}

// 删除工作流
const deleteWorkflow = async (id: string) => {
	try {
		await ElMessageBox.confirm(t('pages.dashboard.deleteConfirm.message'), t('common.dialog.tip'), {
			confirmButtonText: t('common.confirm'),
			cancelButtonText: t('common.cancel'),
			type: 'warning'
		})

		// 从本地存储删除
		const projectMap = JSON.parse(localStorage.getItem(`workflow-map`) || '{}')
		delete projectMap[id]
		localStorage.setItem(`workflow-map`, JSON.stringify(projectMap))

		// 更新列表
		recentWorkflows.value = recentWorkflows.value.filter((item) => item.id !== id)

		ElMessage.success(t('pages.dashboard.deleteConfirm.success'))
	} catch {
		// 用户取消
	}
}

// 从本地存储加载工作流
const projectMap = JSON.parse(localStorage.getItem(`workflow-map`) || '{}')
const recentWorkflows = ref([
	...Object.entries(projectMap)
		.map(([_id, workflow]) => workflow)
		.map((item: any) => ({
			...item,
			id: item.id,
			title: item.name,
			created: item.created || t('common.date.recent')
		}))
])

agent
	.postAgentGetAgentList({
		pageIndex: 1
	})
	.then((res) => {
		if (res.result?.model?.length) {
			recentWorkflows.value = res.result.model.map((item: any) => ({
				...item,
				id: item.id,
				title: item.name,
				created: item.created || t('common.date.recent')
			}))
		}
	})

const recentActivities = computed(
	() =>
		(tm('pages.dashboard.activities') as Array<{
			id: number
			icon: string
			type: string
			text: string
			time: string
		}>) || []
)

const templates = computed(
	() =>
		(tm('pages.dashboard.templates') as Array<{
			id: number
			name: string
			desc: string
			icon: string
			category: string
		}>) || []
)
</script>

<style lang="less" scoped>
.dashboard-container {
	//height: calc(100vh - 48px);
	padding: 24px;
	//display: flex;
	//flex-direction: column;
	//overflow: hidden;
}

.welcome-banner {
	background: linear-gradient(135deg, #ff6b6b 0%, #764ba2 100%);
	border-radius: 12px;
	padding: 32px 40px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
	color: white;

	.welcome-content {
		h1 {
			font-size: 28px;
			font-weight: 700;
			margin: 0 0 8px 0;
		}

		p {
			font-size: 14px;
			margin: 0;
			opacity: 0.9;
		}
	}
}

.stats-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 16px;
	margin-bottom: 32px;
}

.stat-card {
	background: var(--bg-base);
	border-radius: 12px;
	padding: 20px;
	display: flex;
	align-items: center;
	gap: 16px;
	cursor: pointer;
	transition: all 0.3s;
	box-shadow: var(--shadow-sm);

	&:hover {
		box-shadow: var(--shadow-md);
		transform: translateY(-2px);
	}

	.stat-icon {
		width: 48px;
		height: 48px;
		border-radius: 10px;
		display: flex;
		align-items: center;
		justify-content: center;

		&.purple {
			background: #f3e8ff;
			color: #9333ea;
		}

		&.blue {
			background: #dbeafe;
			color: #2563eb;
		}

		&.green {
			background: #dcfce7;
			color: #16a34a;
		}

		&.orange {
			background: #fed7aa;
			color: #ea580c;
		}
	}

	.stat-info {
		flex: 1;

		.stat-value {
			font-size: 24px;
			font-weight: 700;
			color: var(--text-primary);
			margin-bottom: 4px;
		}

		.stat-label {
			font-size: 13px;
			color: var(--text-secondary);
		}
	}

	.stat-trend {
		font-size: 13px;
		font-weight: 600;

		&.up {
			color: #16a34a;
		}

		&.down {
			color: #dc2626;
		}
	}
}

.quick-actions-section {
	margin-bottom: 32px;

	h2 {
		font-size: 18px;
		font-weight: 600;
		margin: 0 0 16px 0;
		color: var(--text-primary);
	}
}

.actions-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 16px;
}

.action-card {
	background: var(--bg-base);
	border-radius: 12px;
	padding: 24px;
	text-align: center;
	cursor: pointer;
	transition: all 0.3s;
	box-shadow: var(--shadow-sm);

	&:hover {
		box-shadow: var(--shadow-md);
		transform: translateY(-2px);

		.action-icon {
			background: var(--el-color-primary);
			color: white;
		}
	}

	.action-icon {
		width: 56px;
		height: 56px;
		border-radius: 12px;
		background: var(--bg-container);
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 12px;
		transition: all 0.3s;
		color: var(--text-secondary);
	}

	.action-title {
		font-size: 15px;
		font-weight: 600;
		color: var(--text-primary);
		margin-bottom: 4px;
	}

	.action-desc {
		font-size: 13px;
		color: var(--text-secondary);
	}
}

.main-content-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 24px;
	margin-bottom: 32px;
	min-height: 0;
}

.content-panel {
	background: var(--bg-base);
	border-radius: 12px;
	padding: 24px;
	box-shadow: var(--shadow-sm);
	flex-direction: column;

	&:first-child {
		.workflow-list {
			max-height: 280px;
			overflow-y: auto;
			padding-right: 8px;

			&::-webkit-scrollbar {
				width: 6px;
			}

			&::-webkit-scrollbar-track {
				background: transparent;
			}

			&::-webkit-scrollbar-thumb {
				background: #d1d5db;
				border-radius: 3px;

				&:hover {
					background: #9ca3af;
				}
			}
		}
	}

	&:last-child {
		.activity-list {
			max-height: 280px;
			overflow-y: auto;
			padding-right: 8px;

			&::-webkit-scrollbar {
				width: 6px;
			}

			&::-webkit-scrollbar-track {
				background: transparent;
			}

			&::-webkit-scrollbar-thumb {
				background: #d1d5db;
				border-radius: 3px;

				&:hover {
					background: #9ca3af;
				}
			}
		}
	}
}

.panel-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;

	h2,
	h3 {
		font-size: 18px;
		font-weight: 600;
		margin: 0;
		color: var(--text-primary);
	}
}

.workflow-list {
	display: flex;
	flex-direction: column;
	gap: 12px;
}

.workflow-item {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 12px;
	border-radius: 8px;
	transition: all 0.2s;
	cursor: pointer;

	&:hover {
		background: var(--bg-container);
	}

	.workflow-icon {
		width: 40px;
		height: 40px;
		border-radius: 8px;
		background: #f3e8ff;
		color: #9333ea;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.workflow-main {
		flex: 1;

		.workflow-title {
			font-size: 14px;
			font-weight: 600;
			color: var(--text-primary);
			margin-bottom: 4px;
		}

		.workflow-meta {
			font-size: 12px;
			color: var(--text-secondary);
		}
	}
}

.activity-list {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.activity-item {
	display: flex;
	align-items: flex-start;
	gap: 12px;

	.activity-icon {
		width: 32px;
		height: 32px;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;

		&.success {
			background: #dcfce7;
			color: #16a34a;
		}

		&.info {
			background: #dbeafe;
			color: #2563eb;
		}
	}

	.activity-main {
		flex: 1;

		.activity-text {
			font-size: 14px;
			color: var(--text-primary);
			margin-bottom: 4px;
		}

		.activity-time {
			font-size: 12px;
			color: var(--text-tertiary);
		}
	}
}

.templates-section {
	margin-bottom: 32px;
	// overflow: hidden;
}

.templates-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 16px;
}

.template-card {
	background: var(--bg-base);
	border-radius: 12px;
	padding: 20px;
	cursor: pointer;
	transition: all 0.3s;
	box-shadow: var(--shadow-sm);
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;

	&:hover {
		box-shadow: var(--shadow-md);
		transform: translateY(-2px);
	}

	.template-icon {
		width: 48px;
		height: 48px;
		border-radius: 10px;
		background: var(--bg-container);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 12px;
		color: var(--el-color-primary);
	}

	.template-title {
		font-size: 15px;
		font-weight: 600;
		color: var(--text-primary);
		margin-bottom: 6px;
	}

	.template-desc {
		font-size: 13px;
		color: var(--text-secondary);
		margin-bottom: 12px;
		min-height: 26px;
	}
}

.cursor-pointer {
	cursor: pointer;
}
</style>
