<template>
	<el-drawer
		v-model="visible"
		direction="rtl"
		:title="currentModelId ? t('pages.model.editTitle') : t('pages.model.createTitle')"
		width="700px"
	>
		<el-form
			ref="formRef"
			:model="modelForm"
			:rules="modelRules"
			label-width="120px"
			label-position="top"
		>
			<el-form-item :label="t('pages.model.fields.source')" prop="source">
				<el-radio-group v-model="modelForm.source" @change="$emit('source-change')">
					<el-radio label="local">{{ t('pages.model.sources.localOllama') }}</el-radio>
					<el-radio label="remote">{{ t('pages.model.sources.remote') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item v-if="modelForm.source === 'remote'" :label="t('pages.model.fields.type')" prop="type">
				<el-select
					v-model="modelForm.type"
					:placeholder="t('pages.model.placeholders.type')"
					@change="$emit('type-change')"
				>
					<el-option :label="t('pages.model.types.KnowledgeQA')" value="KnowledgeQA" />
					<el-option :label="t('pages.model.types.Embedding')" value="Embedding" />
					<el-option :label="t('pages.model.types.Rerank')" value="Rerank" />
					<el-option :label="t('pages.model.types.VLLM')" value="VLLM" />
				</el-select>
			</el-form-item>

			<el-form-item v-if="modelForm.source === 'local'" :label="t('pages.model.fields.localModel')" prop="name">
				<el-select v-model="modelForm.name" :placeholder="t('pages.model.placeholders.select')" style="width: 100%">
					<el-option
						v-for="model in availableLocalModels"
						:key="model.name"
						:label="model.name"
						:value="model.name"
					/>
				</el-select>
			</el-form-item>

			<el-form-item v-if="modelForm.source === 'remote'" :label="t('pages.model.fields.provider')" prop="provider">
				<el-select
					v-model="modelForm.provider"
					:placeholder="t('pages.model.placeholders.provider')"
					style="width: 100%"
					@change="$emit('provider-change')"
				>
					<el-option v-for="p in providers" :key="p.value" :label="p.label" :value="p.value" />
				</el-select>
			</el-form-item>

			<el-form-item :label="t('pages.model.fields.name')" prop="name">
				<el-input
					v-model="modelForm.name"
					:readonly="modelForm.source === 'local'"
					:placeholder="t('pages.model.placeholders.name')"
				/>
			</el-form-item>

			<el-form-item :label="t('pages.model.fields.title')" prop="title">
				<el-input v-model="modelForm.title" :placeholder="t('pages.model.placeholders.title')" />
			</el-form-item>

			<el-form-item :label="t('pages.model.fields.description')" prop="description">
				<el-input
					v-model="modelForm.description"
					type="textarea"
					rows="2"
					:placeholder="t('pages.model.placeholders.description')"
				/>
			</el-form-item>

			<el-form-item v-if="modelForm.source === 'remote'" :label="t('pages.model.fields.baseUrl')" prop="base_url">
				<el-autocomplete
					v-model="modelForm.base_url"
					:fetch-suggestions="queryBaseUrlSuggestions"
					clearable
					:placeholder="t('pages.model.placeholders.baseUrl')"
					style="width: 100%"
				/>
			</el-form-item>

			<el-form-item
				v-if="modelForm.source === 'remote' && !currentModelId"
				:label="t('pages.model.fields.apiKey')"
				prop="api_key"
			>
				<el-input v-model="modelForm.api_key" type="password" :placeholder="t('pages.model.placeholders.apiKey')" />
			</el-form-item>
			<el-form-item
				v-if="modelForm.source === 'remote' && modelForm.type === 'Embedding'"
				:label="t('pages.model.fields.dimension')"
				prop="dimension"
			>
				<el-input-number
					v-model="modelForm.dimension"
					:min="1"
					:step="1"
					controls-position="right"
					style="width: 100%"
					:placeholder="t('pages.model.placeholders.dimension')"
				/>
			</el-form-item>

			<el-form-item
				v-if="modelForm.source === 'remote' && modelForm.type === 'Embedding'"
				:label="t('pages.model.fields.truncateTokens')"
				prop="truncate_prompt_tokens"
			>
				<el-input-number
					v-model="modelForm.truncate_prompt_tokens"
					:min="-1"
					:step="1"
					controls-position="right"
					style="width: 100%"
					:placeholder="t('pages.model.placeholders.truncateTokens')"
				/>
			</el-form-item>

			<el-form-item
				v-if="modelForm.source === 'remote' && modelForm.type === 'KnowledgeQA'"
				:label="t('pages.model.fields.supportsVision')"
				prop="supports_vision"
			>
				<el-switch v-model="modelForm.supports_vision" />
			</el-form-item>

			<el-form-item
				v-if="modelForm.source === 'remote' && modelForm.type === 'KnowledgeQA'"
				:label="t('pages.model.fields.thinkingControl')"
				prop="thinking_control"
			>
				<el-select
					v-model="modelForm.thinking_control"
					:placeholder="t('pages.model.placeholders.thinkingControl')"
					popper-class="thinking-control-select"
					style="width: 100%"
				>
					<el-option
						v-for="option in thinkingControlOptions"
						:key="option.value"
						:label="option.title"
						:value="option.value"
					>
						<div class="thinking-option">
							<div class="thinking-option__title">{{ option.title }}</div>
							<div class="thinking-option__desc">{{ option.description }}</div>
						</div>
					</el-option>
				</el-select>
				<div class="field-tip">
					{{ t('pages.model.thinking.tip') }}
				</div>
			</el-form-item>

			<el-form-item prop="custom_headers">
				<div class="header-config">
					<div class="header-config__top">
						<span>{{ t('pages.model.fields.customHeaders') }}</span>
						<el-button type="primary" link @click="$emit('add-custom-header')">
							<el-icon>
								<Plus />
							</el-icon>
							{{ t('pages.model.addHeader') }}
						</el-button>
					</div>
					<div class="header-config__desc">
						{{ t('pages.model.customHeadersDesc') }}
					</div>
					<div class="header-config__rows">
						<div v-for="(item, index) in customHeaderList" :key="index" class="header-config__row">
							<el-input v-model="item.key" :placeholder="t('pages.model.placeholders.headerName')" />
							<el-input v-model="item.value" :placeholder="t('pages.model.placeholders.headerValue')" />
							<el-button
								link
								type="danger"
								:disabled="customHeaderList.length === 1"
								@click="$emit('remove-custom-header', index)"
							>
								{{ t('common.delete') }}
							</el-button>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item>
				<div v-if="modelForm.source === 'remote'" class="model-check-box">
					<el-button type="primary" plain :loading="formCheckLoading" @click="$emit('check')">
						{{ t('pages.model.testConnection') }}
					</el-button>
					<el-alert
						v-if="formCheckResult.message"
						:type="formCheckResult.success ? 'success' : 'error'"
						:title="formCheckResult.message"
						:closable="false"
						show-icon
					/>
				</div>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">{{ t('common.cancel') }}</el-button>
			<el-button type="primary" :loading="submitLoading" @click="$emit('submit')">{{ t('pages.model.submit') }}</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useI18n } from '@/composables/useI18n'
import type {
	ModelCreateForm,
	ModelProvider,
	OllamaModel,
	ThinkingControlType
} from '../types'

const { t } = useI18n()

const props = defineProps<{
	modelValue: boolean
	currentModelId: string | null
	modelForm: ModelCreateForm
	modelRules: Record<string, any>
	availableLocalModels: OllamaModel[]
	providers: ModelProvider[]
	customHeaderList: Array<{ key: string; value: string }>
	thinkingControlOptions: Array<{
		title: string
		description: string
		value: ThinkingControlType
	}>
	formCheckLoading: boolean
	formCheckResult: {
		success: boolean
		message: string
	}
	submitLoading: boolean
	queryBaseUrlSuggestions: (
		queryString: string,
		cb: (results: Array<{ value: string }>) => void
	) => void
}>()

const emit = defineEmits<{
	(e: 'update:modelValue', value: boolean): void
	(e: 'source-change'): void
	(e: 'type-change'): void
	(e: 'provider-change'): void
	(e: 'add-custom-header'): void
	(e: 'remove-custom-header', index: number): void
	(e: 'check'): void
	(e: 'submit'): void
}>()

const formRef = ref()

const visible = computed({
	get: () => props.modelValue,
	set: (value) => emit('update:modelValue', value)
})

defineExpose({
	validate: (...args: any[]) => formRef.value?.validate?.(...args),
	validateField: (...args: any[]) => formRef.value?.validateField?.(...args),
	clearValidate: (...args: any[]) => formRef.value?.clearValidate?.(...args),
	resetFields: (...args: any[]) => formRef.value?.resetFields?.(...args)
})
</script>

<style scoped lang="less">
.field-tip {
	margin-top: 8px;
	color: var(--text-tertiary);
	font-size: 12px;
	line-height: 1.6;
}

.thinking-option {
	display: flex;
	flex-direction: column;
	justify-content: center;
	min-height: 54px;
	padding: 6px 0;
	line-height: 1.35;
}

.thinking-option__title {
	color: var(--text-primary);
	font-size: 13px;
	font-weight: 600;
}

.thinking-option__desc {
	margin-top: 3px;
	color: var(--text-tertiary);
	font-size: 12px;
	white-space: normal;
}

:global(.thinking-control-select .el-select-dropdown__item) {
	height: auto;
	min-height: 62px;
	padding-top: 4px;
	padding-bottom: 4px;
}

.header-config {
	width: 100%;
}

.header-config__top {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.header-config__desc {
	color: var(--text-tertiary);
	font-size: 12px;
	margin: 4px 0 10px;
}

.header-config__rows {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.header-config__row {
	display: grid;
	grid-template-columns: 1fr 1fr auto;
	gap: 8px;
	align-items: center;
}

.model-check-box {
	width: 100%;
	display: flex;
	flex-direction: column;
	gap: 8px;
}

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