<template>
	<div class="agent-page">
		<div class="page-header">
			<div class="header-title">
				<h1>{{ t('pages.agent.title') }}</h1>
			</div>
		</div>

		<div class="stats">
			<div class="stat-card">
				<div class="stat-value">{{ pagination.totalCount }}</div>
				<div class="stat-label">{{ t('pages.agent.total') }}</div>
			</div>
			<div class="stat-card">
				<div class="stat-value">{{ list.length }}</div>
				<div class="stat-label">{{ t('pages.agent.currentPageCount') }}</div>
			</div>
			<div class="stat-card">
				<div class="stat-value">{{ publishedCount }}</div>
				<div class="stat-label">{{ t('pages.agent.published') }}</div>
			</div>
		</div>

		<el-card class="panel">
			<div class="toolbar">
				<div class="toolbar-left">
					<el-input
						v-model="filters.keyword"
						clearable
						:placeholder="t('pages.agent.searchPlaceholder')"
						class="search-input"
						@keyup.enter="handleSearch"
					>
						<template #prefix>
							<el-icon>
								<Search />
							</el-icon>
						</template>
					</el-input>
					<el-select
						v-model="filters.mode"
						clearable
						:placeholder="t('pages.agent.mode')"
						style="width: 160px"
						@change="handleSearch"
					>
						<el-option :label="t('pages.agent.modeQuickAnswer')" value="quick-answer" />
						<el-option :label="t('pages.agent.modeSmartReasoning')" value="smart-reasoning" />
					</el-select>
					<div class="toolbar-actions">
						<el-button type="primary" @click="handleSearch">
							<el-icon><Search /></el-icon>
							{{ t('common.search') }}
						</el-button>
						<el-button @click="handleReset">
							<el-icon><RefreshRight /></el-icon>
							{{ t('pages.agent.reset') }}
						</el-button>
					</div>
				</div>
				<div class="toolbar-right">
					<el-button type="primary" @click="openCreateDrawer">
						<el-icon><Plus /></el-icon>
						{{ t('pages.agent.createAgent') }}
					</el-button>
				</div>
			</div>

			<div v-loading="loading" class="grid">
				<el-empty
					v-if="!visibleList.length && !loading"
					:description="t('pages.agent.emptyDescription')"
					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 || t('pages.agent.unnamedAgent') }}</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!)">{{
														t('common.edit')
													}}</el-button>
												</el-dropdown-item>
												<el-dropdown-item>
													<el-button link type="danger" @click="removeItem(item.id!)">{{
														t('common.delete')
													}}</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 || t('pages.agent.unnamedAgent') }}</div>
						<div class="desc">{{ item.description || t('pages.agent.noDescription') }}</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!)">{{
												t('common.edit')
											}}</el-button>
										</el-dropdown-item>
										<el-dropdown-item>
											<el-button link type="danger" @click="removeItem(item.id!)">{{
												t('common.delete')
											}}</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, prev, pager, next"
					:total="pagination.totalCount"
					@current-change="handlePageChange"
					@size-change="handleSizeChange"
				/>
			</div>
		</el-card>

		<EditModal v-model="drawerVisible" :agent-id="currentId" @saved="handleSaved" />
		<DetailModal v-model="detailVisible" :detail-item="detailItem" :model-name-map="modelNameMap" />
	</div>
</template>

<script setup lang="ts">
// 1. Type imports
import type { AgentItem, ModelItem } from './type'

// 2. Composables
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Plus, Search, MoreFilled, RefreshRight } from '@element-plus/icons-vue'
import { agentApplication, aiModel } from '@repo/api-service'
import { useI18n } from '@/composables/useI18n'
import EditModal from './components/EditModal.vue'
import DetailModal from './components/DetailModal.vue'

const { t } = useI18n()

// 4. Reactive state
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 modelNameMap = ref<Record<string, string>>({})

// 5. Computed properties
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
)

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

function formatModeLabel(mode?: string) {
	if (mode === 'quick-answer') return t('pages.agent.modeQuickAnswer')
	if (mode === 'smart-reasoning') return t('pages.agent.modeSmartReasoning')
	if (mode === 'agent') return 'Agent'
	return t('pages.agent.modeUnset')
}

function formatTypeLabel(type?: string) {
	if (type === 'knowledgeqa') return 'Knowledge'
	if (type === 'agent') return 'Agent'
	return type || '-'
}

async function loadModelNameMap() {
	const res = await aiModel.postModelSelectList({
		keyword: '',
		type: ''
	})

	const nextMap: Record<string, string> = {}
	;(res?.result || []).forEach((item) => {
		if (item.id) {
			nextMap[item.id] = item.title || '-'
		}
	})
	modelNameMap.value = nextMap
}

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(
			t('pages.agent.deleteConfirm'),
			t('pages.agent.deleteConfirmTitle'),
			{ type: 'warning' }
		)
		await agentApplication.postAiAgentOpenApiDelete({ id })
		loadList(pagination.pageIndex)
	} catch {
		// ignore
	}
}

// 7. Lifecycle
onMounted(async () => {
	await Promise.all([loadList(1), loadModelNameMap()])
})
</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 var(--border-light);
	background: var(--bg-base);
}

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

.stat-label {
	margin-top: 4px;
	color: var(--text-tertiary);
}

.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;
}

.toolbar-actions {
	display: flex;
	align-items: center;
	gap: 8px;

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

.search-input {
	width: 280px;
}

.pill {
	padding: 8px 12px;
	border-radius: 999px;
	border: 1px solid var(--border-light);
	background: var(--bg-container);
	font-size: 12px;
	color: var(--text-tertiary);
}

.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 var(--border-light);
	background: var(--bg-base);
	box-shadow: var(--shadow-sm);
	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: var(--border-base);
	box-shadow: var(--shadow-md);
}

.card-head {
	display: flex;
	align-items: center;
	gap: 14px;
	padding: 14px 16px;
	border-radius: 18px;
	background: var(--card-bg-unselected);
}

.emoji-avatar {
	width: 68px;
	height: 68px;
	border-radius: 20px;
	display: grid;
	place-items: center;
	flex-shrink: 0;
	font-size: 34px;
	background: var(--bg-overlay);
	box-shadow:
		inset 0 1px 0 rgba(255, 255, 255, 0.2),
		0 12px 24px rgba(0, 0, 0, 0.08);
}

.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: var(--bg-overlay);
	font-size: 12px;
	color: var(--text-primary);
	border: 1px solid var(--border-light);
}

.badge.subtle {
	background: var(--text-strong);
	color: var(--bg-base);
	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: var(--text-strong);
	word-break: break-word;
}

.desc {
	min-height: 44px;
	color: var(--text-secondary);
	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: var(--text-secondary);
	background: var(--bg-overlay);
	transition:
		background 0.2s ease,
		color 0.2s ease;
}

.actions-trigger:hover {
	background: var(--bg-container);
	color: var(--text-strong);
}

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

.meta-chip {
	max-width: 100%;
	padding: 6px 10px;
	border-radius: 999px;
	background: var(--bg-container);
	border: 1px solid var(--border-light);
	color: var(--text-secondary);
	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>
