<template>
	<el-dialog v-model="visible" title="选择提示词模版" width="960px" append-to-body>
		<div class="prompt-template-dialog">
			<div class="prompt-template-dialog__meta">
				<span>{{ dialogTitle }}</span>
				<el-button text :icon="Refresh" :loading="loading" @click="loadTemplates"> 刷新 </el-button>
			</div>
			<div v-loading="loading" class="prompt-template-grid">
				<el-empty v-if="!options.length && !loading" description="暂无可用模版" />
				<div
					v-for="template in options"
					: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>
		<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 { computed, ref, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { resource } from '@repo/api-service'
type PromptTemplateConfigResponse = Awaited<ReturnType<typeof resource.postPromptTemplateConfig>>
type PromptTemplateConfig = NonNullable<PromptTemplateConfigResponse['result']>

type PromptTemplateItem = {
	content: string
	default: boolean
	description: string
	has_knowledge_base: boolean
	has_web_search: boolean
	id: string
	is_builtin: boolean
	mode: string
	name: string
	type: string
	user?: string
	value: string
}

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

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

const props = defineProps<{
	field: PromptFieldKey
	mode: string
}>()

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

const loading = ref(false)
const config = ref<PromptTemplateConfig | null>(null)
const options = ref<PromptTemplateItem[]>([])
const selectedTemplate = ref<PromptTemplateItem | null>(null)

const dialogTitle = computed(() => {
	const titleMap: Record<PromptFieldKey, string> = {
		systemPrompt: '系统提示词模版',
		contextTemplate: '上下文模板模版',
		rewritePromptSystem: '改写系统提示词模版',
		rewritePromptUser: '改写用户提示词模版',
		fallbackPrompt: '兜底提示词模版'
	}
	return titleMap[props.field]
})

function getTemplateItems(field: PromptFieldKey) {
	if (!config.value) return [] as PromptTemplateItem[]
	switch (field) {
		case 'systemPrompt':
			return props.mode === 'smart-reasoning'
				? ([
						...(config.value.agent_system_prompts || []),
						...(config.value.system_prompts || [])
					] as PromptTemplateItem[])
				: ([
						...(config.value.system_prompts || []),
						...(config.value.agent_system_prompts || [])
					] as PromptTemplateItem[])
		case 'contextTemplate':
			return (config.value.context_templates || []) as PromptTemplateItem[]
		case 'rewritePromptSystem':
		case 'rewritePromptUser':
			return (config.value.rewrites || []) as PromptTemplateItem[]
		case 'fallbackPrompt':
			return (config.value.fall_backs || []) as PromptTemplateItem[]
		default:
			return [] as PromptTemplateItem[]
	}
}

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() {
	loading.value = true
	try {
		const res = await resource.postPromptTemplateConfig({})
		if (res.isSuccess && res.result) {
			config.value = res.result as PromptTemplateConfig
			options.value = getTemplateItems(props.field)
			selectedTemplate.value = options.value[0] || null
		}
	} finally {
		loading.value = false
	}
}

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

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

watch(
	() => [props.field, props.mode],
	() => {
		if (!config.value) return
		options.value = getTemplateItems(props.field)
		selectedTemplate.value = options.value[0] || null
	}
)
</script>

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

.prompt-template-dialog__meta {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 12px;
	font-size: 14px;
	font-weight: 600;
	color: #111827;
}

.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 #e5e7eb;
	background: #fff;
	cursor: pointer;
	transition: border-color 0.15s ease;
	box-shadow: 0 12px 24px rgba(15, 23, 42, 0.05);
}

.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: #111827;
}

.prompt-template-card__desc {
	margin-top: 6px;
	font-size: 13px;
	line-height: 1.6;
	color: #6b7280;
}

.prompt-template-card__meta {
	display: flex;
	flex-wrap: wrap;
	gap: 8px 12px;
	margin-top: 12px;
	font-size: 12px;
	color: #6b7280;
}

.prompt-template-card__content {
	margin-top: 12px;
	padding: 12px;
	border-radius: 12px;
	background: #f8fafc;
	color: #334155;
	font-size: 13px;
	line-height: 1.6;
	white-space: pre-wrap;
	max-height: 160px;
	overflow: auto;
}

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