<template>
	<el-dialog v-model="visible" title="提示词模版选择" width="960px" append-to-body>
		<div class="prompt-template-dialog">
			<div class="prompt-template-toolbar">
				<el-input
					v-model="keyword"
					clearable
					placeholder="搜索提示词名称 / 描述"
					class="prompt-template-search"
					@keyup.enter="loadTemplates(1)"
				/>
				<!-- <el-select
					v-model="typeFilter"
					clearable
					placeholder="类型"
					style="width: 180px"
					:options="typeList"
					@change="loadTemplates(1)"
				/> -->
				<el-button @click="loadTemplates(1)">查询</el-button>
				<el-button @click="handleReset">重置</el-button>
				<el-button text :icon="Refresh" :loading="loading" @click="loadTemplates()">刷新</el-button>
			</div>
			<div v-loading="loading" class="prompt-template-grid">
				<el-empty v-if="!list.length && !loading" description="暂无可用模版" />
				<div
					v-for="template in list"
					:key="template.id"
					class="prompt-template-card"
					:class="{ 'is-active': selectedTemplate?.id === template.id }"
					@click="selectedTemplate = template"
				>
					<div class="prompt-template-card__top">
						<div>
							<div class="prompt-template-card__title">
								<el-tag v-if="template.is_builtin" type="success" effect="light">内置</el-tag>
								<el-tag v-if="template.default" type="warning" effect="light">默认</el-tag>
								{{ template.name }}
							</div>
							<div class="prompt-template-card__desc">{{ template.description || '暂无描述' }}</div>
						</div>
					</div>
					<div class="prompt-template-card__meta">
						<span>类型：{{ formatTemplateType(template.type) }}</span>
					</div>
					<div class="prompt-template-card__content">
						{{ getTemplatePreview(template) }}
					</div>
				</div>
			</div>
			<div v-if="pagination.totalCount > 0" class="prompt-template-pagination">
				<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>
		</div>
		<template #footer>
			<div class="drawer-footer">
				<div class="text-12px text-gray-500">当前选择：{{ selectedTemplate?.name }}</div>
				<div>
					<el-button @click="visible = false">取消</el-button>
					<el-button type="primary" :disabled="!selectedTemplate" @click="confirmTemplate">
						确认
					</el-button>
				</div>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { resource } from '@repo/api-service'

type PromptPageResponse = Awaited<ReturnType<typeof resource.postPromptTemplatePageList>>
type PromptPageResult = NonNullable<PromptPageResponse['result']>
type PromptTemplateItem = PromptPageResult['model'][number]

const typeMap = {
	'system-prompt': '系统提示词',
	'agent-system-prompt': 'Agent 系统提示词',
	rewrite: '改写提示词',
	'fall-back': '回退提示词',
	'context-template': '上下文模板',
	'generate-session-title': '生成会话标题',
	'generate-summary': '生成概要',
	'keywords-extraction': '关键词提取'
} as const

export type PromptFieldKey =
	| 'systemPrompt'
	| 'contextTemplate'
	| 'rewritePromptSystem'
	| 'rewritePromptUser'
	| 'fallbackPrompt'

export type PromptTemplateType = keyof typeof typeMap

const visible = defineModel<boolean>({ required: true })

const props = defineProps<{
	field: PromptFieldKey
	type?: PromptTemplateType
}>()

const emit = defineEmits<{
	confirm: [content: string]
}>()

const loading = ref(false)
const keyword = ref('')
const typeFilter = ref('')
const list = ref<PromptTemplateItem[]>([])
const selectedTemplate = ref<PromptTemplateItem | null>(null)

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

const typeList = Object.keys(typeMap).map((type) => ({
	label: typeMap[type as PromptTemplateType],
	value: type
}))

function getTemplateContent(item: PromptTemplateItem) {
	if (props.field === 'rewritePromptUser') return item.user || item.content || ''
	return item.content || ''
}

function formatTemplateType(type?: string) {
	const typeMap: Record<string, string> = {
		'system-prompt': '系统提示词',
		'agent-system-prompt': 'Agent 系统提示词',
		rewrite: '改写提示词',
		'fall-back': '回退提示词',
		'context-template': '上下文模板'
	}
	return typeMap[type || ''] || type || '-'
}

function getTemplatePreview(item: PromptTemplateItem) {
	return (item.content || item.user || '-').slice(0, 120)
}

async function loadTemplates(pageIndex = pagination.pageIndex) {
	loading.value = true
	try {
		const res = await resource.postPromptTemplatePageList({
			pageIndex,
			pageSize: pagination.pageSize,
			keyword: keyword.value,
			type: typeFilter.value
		})
		if (res.isSuccess && res.result) {
			list.value = (res.result.model || []) as PromptTemplateItem[]
			pagination.pageIndex = res.result.currentPage || pageIndex
			pagination.totalCount = res.result.totalCount || 0
			pagination.totalPages = res.result.totalPages || 0
			pagination.pageSize = res.result.pageSize || pagination.pageSize
			selectedTemplate.value = list.value[0] || null
		}
	} finally {
		loading.value = false
	}
}

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

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

function handleReset() {
	keyword.value = ''
	typeFilter.value = props.type!
	loadTemplates(1)
}

function confirmTemplate() {
	if (!selectedTemplate.value) return
	emit('confirm', getTemplateContent(selectedTemplate.value))
	visible.value = false
}

watch(
	() => visible.value,
	(value) => {
		if (!value) return
		selectedTemplate.value = null
		typeFilter.value = props.type!
		loadTemplates(1)
	}
)

watch(
	() => [props.field, props.type],
	() => {
		typeFilter.value = props.type!
		if (visible.value) loadTemplates(1)
	}
)
</script>

<style scoped>
.prompt-template-dialog {
	display: flex;
	flex-direction: column;
	gap: 14px;
}

.prompt-template-toolbar {
	display: flex;
	align-items: center;
	gap: 10px;
	flex-wrap: wrap;
}

.prompt-template-search {
	width: 280px;
}

.prompt-template-grid {
	display: grid;
	grid-template-columns: repeat(2, minmax(0, 1fr));
	gap: 12px;
	max-height: 62vh;
	overflow: auto;
	padding-right: 4px;
}

.prompt-template-grid .el-empty {
	grid-column: 1 / -1;
}

.prompt-template-card {
	padding: 16px;
	border-radius: 18px;
	border: 1px solid var(--border-light);
	background: var(--bg-base);
	cursor: pointer;
	transition: border-color 0.15s ease;
	box-shadow: var(--shadow-sm);
}

.prompt-template-card.is-active {
	border-color: #3b82f6;
}

.prompt-template-card__top {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 10px;
}

.prompt-template-card__title {
	display: flex;
	align-items: center;
	gap: 4px;
	flex-wrap: wrap;
	font-size: 18px;
	font-weight: 700;
	color: var(--text-primary);
}

.prompt-template-card__desc {
	margin-top: 6px;
	font-size: 13px;
	line-height: 1.6;
	color: var(--text-tertiary);
}

.prompt-template-card__meta {
	display: flex;
	flex-wrap: wrap;
	gap: 8px 12px;
	margin-top: 12px;
	font-size: 12px;
	color: var(--text-tertiary);
}

.prompt-template-card__content {
	margin-top: 12px;
	padding: 12px;
	border-radius: 12px;
	background: var(--bg-container);
	color: var(--text-primary);
	font-size: 13px;
	line-height: 1.6;
	white-space: pre-wrap;
	max-height: 160px;
	overflow: auto;
}

.prompt-template-pagination {
	display: flex;
	justify-content: flex-end;
}

.drawer-footer {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	justify-content: space-between;
	gap: 10px;
}

@media (max-width: 768px) {
	.prompt-template-grid {
		grid-template-columns: 1fr;
	}
}
</style>
