<template>
	<div class="agent-page">
		<div class="page-header">
			<div class="header-title">
				<h1>智能体管理</h1>
			</div>
		</div>

		<div class="stats">
			<div class="stat-card">
				<div class="stat-value">{{ pagination.totalCount }}</div>
				<div class="stat-label">总数</div>
			</div>
			<div class="stat-card">
				<div class="stat-value">{{ list.length }}</div>
				<div class="stat-label">当前页数量</div>
			</div>
			<div class="stat-card">
				<div class="stat-value">{{ publishedCount }}</div>
				<div class="stat-label">已发布</div>
			</div>
		</div>

		<el-card class="panel">
			<el-button type="primary" class="mb-12px" @click="openCreateDrawer">
				<el-icon>
					<Plus />
				</el-icon>
				新建智能体
			</el-button>
			<div class="toolbar">
				<div class="toolbar-left">
					<el-input v-model="filters.keyword" clearable placeholder="搜索名称 / ID" class="search-input"
						@keyup.enter="handleSearch">
						<template #prefix>
							<el-icon>
								<Search />
							</el-icon>
						</template>
					</el-input>
					<el-select v-model="filters.mode" clearable placeholder="模式" style="width: 160px" @change="handleSearch">
						<el-option label="问答模式" value="quick-answer" />
						<el-option label="智能推理模式" value="smart-reasoning" />
					</el-select>
					<!-- <el-select
						v-model="filters.type"
						clearable
						placeholder="类型"
						style="width: 160px"
						@change="handleSearch"
					>
						<el-option label="rag-qa" value="rag-qa" />
						<el-option label="agent" value="agent" />
					</el-select> -->
					<el-button @click="handleReset">重置</el-button>
				</div>
			</div>

			<div v-loading="loading" class="grid">
				<el-empty v-if="!visibleList.length && !loading" description="暂无智能体" class="empty" />

				<div v-for="item in visibleList" :key="item.id" class="card" @click="openDetail(item.id)">
					<div class="card-head">
						<div class="emoji-avatar">{{ getAgentEmoji(item.avatar) }}</div>
						<div class="card-head__content">
							<div class="card-head__top">
								<div class="title">{{ item.name || '未命名智能体' }}</div>
								<div class="actions" @click.stop>
									<el-dropdown :hide-on-click="false">
										<span class="actions-trigger">
											<el-icon>
												<MoreFilled />
											</el-icon>
										</span>
										<template #dropdown>
											<el-dropdown-menu>
												<el-dropdown-item>
													<el-button link type="primary" @click="openEditDrawer(item.id)">编辑</el-button>
												</el-dropdown-item>
												<el-dropdown-item>
													<el-button link type="danger" @click="removeItem(item.id)">删除</el-button>
												</el-dropdown-item>
											</el-dropdown-menu>
										</template>
									</el-dropdown>
								</div>
							</div>
							<div class="card-subtitle">
								<span class="badge">{{ formatModeLabel(item.mode) }}</span>
								<span class="badge subtle">{{ formatTypeLabel(item.type) }}</span>
							</div>
						</div>
					</div>

					<div class="body">
						<div class="title">{{ item.name || '未命名智能体' }}</div>
						<div class="desc">{{ item.description || '暂无描述' }}</div>


						<!-- <div class="card-meta">
							<span class="meta-chip">{{ formatId(item.id) }}</span>
							<span class="meta-chip">{{ item.config?.model_config?.model_id || '未配置模型' }}</span>
						</div> -->

						<div class="actions" @click.stop>
							<el-dropdown :hide-on-click="false">
								<span class="cursor-pointer">
									<el-icon>
										<MoreFilled />
									</el-icon>
								</span>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item>
											<el-button link type="primary" @click="openEditDrawer(item.id)">编辑</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button link type="danger" @click="removeItem(item.id)">删除</el-button>
										</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>
				</div>
			</div>

			<div class="pagination" v-if="pagination.totalCount">
				<el-pagination v-model:current-page="pagination.pageIndex" v-model:page-size="pagination.pageSize" background
					layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
					:total="pagination.totalCount" @current-change="handlePageChange" @size-change="handleSizeChange" />
			</div>
		</el-card>

		<EditModal v-model="drawerVisible" :agent-id="currentId" @saved="handleSaved" />

		<el-dialog v-model="detailVisible" title="智能体详情" width="720px">
			<el-descriptions v-if="detailItem" :column="1" border>
				<el-descriptions-item label="名称">{{ detailItem.name }}</el-descriptions-item>
				<el-descriptions-item label="模式">{{ detailItem.mode }}</el-descriptions-item>
				<el-descriptions-item label="描述">{{
					detailItem.description || '-'
				}}</el-descriptions-item>
				<el-descriptions-item label="系统提示词">{{
					detailItem.config?.basic_config?.system_prompt || '-'
				}}</el-descriptions-item>
				<el-descriptions-item label="模型 ID">{{
					detailItem.config?.model_config?.model_id || '-'
				}}</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Plus, Search, MoreFilled } from '@element-plus/icons-vue'
import { agentApplication } from '@repo/api-service'
import EditModal from './components/EditModal.vue'
import type { AgentItem } from './type'

const loading = ref(false)
const drawerVisible = ref(false)
const detailVisible = ref(false)
const detailItem = ref<AgentItem | null>(null)
const currentId = ref('')

const pagination = reactive({
	pageIndex: 1,
	pageSize: 20,
	totalCount: 0,
	totalPages: 0,
	currentPage: 1
})

const filters = reactive({
	keyword: '',
	mode: '',
	type: ''
})

const list = ref<AgentItem[]>([])

const visibleList = computed(() => {
	const keyword = filters.keyword.trim().toLowerCase()
	if (!keyword) return list.value
	return list.value.filter((item) =>
		[item.name, item.id, item.description].some((value) => value?.toLowerCase().includes(keyword))
	)
})

const publishedCount = computed(
	() => list.value.filter((item) => item.status === 'published' || item.is_builtin).length
)

function getAgentEmoji(avatar?: string) {
	return avatar?.trim() || '🤖'
}

function formatModeLabel(mode?: string) {
	if (mode === 'quick-answer') return '问答模式'
	if (mode === 'smart-reasoning') return '推理模式'
	if (mode === 'agent') return 'Agent'
	return mode || '未设置模式'
}

function formatTypeLabel(type?: string) {
	if (type === 'knowledgeqa') return 'Knowledge'
	if (type === 'agent') return 'Agent'
	return type || '默认类型'
}

function formatId(id?: string) {
	if (!id) return 'ID 未生成'
	if (id.length <= 14) return id
	return `${id.slice(0, 6)}...${id.slice(-4)}`
}

async function loadList(pageIndex = 1) {
	loading.value = true
	try {
		const res = await agentApplication.postAiAgentPageList({
			keyword: filters.keyword,
			mode: filters.mode,
			type: filters.type,
			pageIndex,
			pageSize: pagination.pageSize
		})
		if (res.isSuccess && res.result) {
			list.value = (res.result.model || []) as AgentItem[]
			pagination.pageIndex = res.result.currentPage || pageIndex
			pagination.currentPage = pagination.pageIndex
			pagination.totalCount = res.result.totalCount || 0
			pagination.totalPages = res.result.totalPages || 0
			pagination.pageSize = res.result.pageSize || pagination.pageSize
		}
	} finally {
		loading.value = false
	}
}

function handleSearch() {
	pagination.pageIndex = 1
	loadList(1)
}

function handleReset() {
	filters.keyword = ''
	filters.mode = ''
	filters.type = ''
	handleSearch()
}

function handlePageChange(page: number) {
	pagination.pageIndex = page
	loadList(page)
}

function handleSizeChange(size: number) {
	pagination.pageSize = size
	loadList(1)
}

function openCreateDrawer() {
	currentId.value = ''
	drawerVisible.value = true
}

function openEditDrawer(id: string) {
	currentId.value = id
	drawerVisible.value = true
}

async function openDetail(id: string) {
	const res = await agentApplication.postAiAgentInfo({ id })
	if (!res.isSuccess || !res.result) {
		return
	}
	detailItem.value = res.result as AgentItem
	detailVisible.value = true
}

function handleSaved() {
	loadList(pagination.pageIndex)
}

async function removeItem(id: string) {
	try {
		await ElMessageBox.confirm('Delete this agent?', 'Confirm', { type: 'warning' })
		await agentApplication.postAiAgentOpenApiDelete({ id })
		loadList(pagination.pageIndex)
	} catch {
		// ignore
	}
}

onMounted(async () => {
	await loadList(1)
})
</script>

<style scoped lang="less">
.agent-page {
	padding: 24px;
}

.page-header {
	display: flex;
	align-items: flex-end;
	justify-content: space-between;
	gap: 20px;
	margin-bottom: 24px;

	.header-title {
		h1 {
			margin: 0;
			font-size: 30px;
			line-height: 1.1;
			color: var(--text-primary);
		}
	}
}

.stats {
	display: grid;
	grid-template-columns: repeat(3, minmax(0, 1fr));
	gap: 12px;
	margin-bottom: 16px;
}

.stat-card {
	padding: 18px;
	border-radius: 18px;
	border: 1px solid #e5e7eb;
	background: #fff;
}

.stat-value {
	font-size: 24px;
	font-weight: 700;
}

.stat-label {
	margin-top: 4px;
	color: #6b7280;
}

.panel {
	border-radius: 18px;
}

.toolbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	margin-bottom: 16px;
	flex-wrap: wrap;
}

.toolbar-left,
.toolbar-right {
	display: flex;
	align-items: center;
	gap: 10px;
	flex-wrap: wrap;
}

.search-input {
	width: 280px;
}

.pill {
	padding: 8px 12px;
	border-radius: 999px;
	border: 1px solid #e5e7eb;
	background: #f8fafc;
	font-size: 12px;
	color: #6b7280;
}

.grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
	gap: 16px;
	min-height: 240px;
}

.card {
	overflow: hidden;
	border-radius: 20px;
	border: 1px solid #e5e7eb;
	background: #fff;
	box-shadow: 0 12px 28px rgba(15, 23, 42, 0.06);
	cursor: pointer;
	padding: 16px;
	display: flex;
	flex-direction: column;
	gap: 14px;
	transition:
		transform 0.22s ease,
		box-shadow 0.22s ease,
		border-color 0.22s ease;
}

.card:hover {
	transform: translateY(-3px);
	border-color: #d8dee9;
	box-shadow: 0 18px 36px rgba(15, 23, 42, 0.1);
}

.card-head {
	display: flex;
	align-items: center;
	gap: 14px;
	padding: 14px 16px;
	border-radius: 18px;
	background:
		radial-gradient(circle at top left, rgba(15, 23, 42, 0.06), transparent 38%),
		linear-gradient(135deg, #f8fafc, #eef2ff 58%, #fff7ed);
}

.emoji-avatar {
	width: 68px;
	height: 68px;
	border-radius: 20px;
	display: grid;
	place-items: center;
	flex-shrink: 0;
	font-size: 34px;
	background: rgba(255, 255, 255, 0.82);
	box-shadow:
		inset 0 1px 0 rgba(255, 255, 255, 0.9),
		0 12px 24px rgba(148, 163, 184, 0.18);
}

.card-head__content {
	min-width: 0;
	flex: 1;
}

.card-head__top {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 12px;
}

.card-subtitle {
	margin-top: 10px;
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.badge {
	padding: 5px 10px;
	border-radius: 999px;
	background: rgba(255, 255, 255, 0.92);
	font-size: 12px;
	color: #334155;
	border: 1px solid rgba(203, 213, 225, 0.9);
}

.badge.subtle {
	background: rgba(15, 23, 42, 0.82);
	color: #f8fafc;
	border-color: transparent;
}

.body {
	padding: 0 2px;
	display: flex;
	flex-direction: column;
	gap: 12px;
}

.title {
	font-size: 18px;
	font-weight: 700;
	line-height: 1.25;
	color: #0f172a;
	word-break: break-word;
}

.desc {
	min-height: 44px;
	color: #64748b;
	font-size: 14px;
	line-height: 1.65;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.tags {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.actions {
	display: flex;
	justify-content: flex-end;
	gap: 8px;
	margin-left: auto;
}

.actions-trigger {
	width: 30px;
	height: 30px;
	border-radius: 999px;
	display: grid;
	place-items: center;
	color: #475569;
	background: rgba(255, 255, 255, 0.8);
	transition:
		background 0.2s ease,
		color 0.2s ease;
}

.actions-trigger:hover {
	background: rgba(15, 23, 42, 0.08);
	color: #0f172a;
}

.card-meta {
	display: flex;
	flex-wrap: wrap;
	gap: 8px;
}

.meta-chip {
	max-width: 100%;
	padding: 6px 10px;
	border-radius: 999px;
	background: #f8fafc;
	border: 1px solid #e2e8f0;
	color: #64748b;
	font-size: 12px;
	line-height: 1.2;
	font-variant-numeric: tabular-nums;
}

.body>.title,
.body>.actions {
	display: none;
}

.pagination {
	display: flex;
	justify-content: flex-end;
	margin-top: 16px;
}

.empty {
	grid-column: 1 / -1;
	padding: 24px 0;
}

@media (max-width: 768px) {

	.page-head,
	.toolbar,
	.stats {
		grid-template-columns: 1fr;
		flex-direction: column;
	}

	.search-input {
		width: 100%;
	}
}
</style>
