<template>
	<el-dialog
		v-model="visible"
		:title="t('pages.toolbar.envDialog.title')"
		width="520px"
		append-to-body
	>
		<div class="space-y-12px">
			<div>{{ t('pages.toolbar.envDialog.description') }}</div>
			<div class="flex items-center justify-between">
				<el-button type="primary" link @click="onAddClick">
					<span class="text-13px">+ {{ t('pages.toolbar.envDialog.addVariable') }}</span>
				</el-button>
			</div>

			<div v-if="envList.length === 0" class="text-12px text-gray-400">
				{{ t('pages.toolbar.envDialog.empty') }}
			</div>

			<div v-else class="space-y-8px max-h-360px overflow-y-auto pr-4px">
				<el-card
					v-for="(item, index) in envList"
					:key="index"
					shadow="never"
					class="env-item-card"
					body-class="p-6px!"
					header-class="p-6px!"
				>
					<template #header>
						<div class="flex items-center justify-between">
							<div class="text-14px text-gray-700 font-medium flex items-center gap-4px">
								<Icon icon="eos-icons:env" class="w-12px h-12px" color="#7839ee" />
								{{ item.name || t('pages.toolbar.envDialog.unnamedVariable') }}
								<span class="ml-2 text-12px text-gray-400">{{ item.type }}</span>
							</div>
							<div class="flex items-center gap-4px">
								<el-button
									type="primary"
									link
									class="mt-4px flex-shrink-0"
									@click="onEditClick(index)"
								>
									{{ t('pages.toolbar.envDialog.edit') }}
								</el-button>
								<el-button
									type="danger"
									link
									class="mt-4px flex-shrink-0"
									@click="removeEnv(index)"
								>
									{{ t('pages.toolbar.envDialog.delete') }}
								</el-button>
							</div>
						</div>
					</template>
					<div class="text-12px text-gray-500 break-all">
						{{ item.value }}
					</div>
				</el-card>
			</div>
		</div>
	</el-dialog>

	<el-dialog
		v-model="editVisible"
		:title="
			editingIndex === -1
				? t('pages.toolbar.envDialog.addDialogTitle')
				: t('pages.toolbar.envDialog.editDialogTitle')
		"
		width="520px"
		append-to-body
	>
		<el-form
			ref="editFormRef"
			:model="editForm"
			:rules="editFormRules"
			label-width="80px"
			label-position="top"
		>
			<el-form-item :label="t('pages.toolbar.envDialog.nameLabel')" prop="name">
				<el-input
					v-model="editForm.name"
					:placeholder="t('pages.toolbar.envDialog.namePlaceholder')"
					clearable
				/>
			</el-form-item>

			<el-form-item :label="t('pages.toolbar.envDialog.typeLabel')" prop="type">
				<el-select
					v-model="editForm.type"
					:placeholder="t('pages.toolbar.envDialog.typePlaceholder')"
					class="w-full"
				>
					<el-option label="String" value="string" />
					<el-option label="Number" value="number" />
				</el-select>
			</el-form-item>

			<el-form-item :label="t('pages.toolbar.envDialog.valueLabel')" prop="value">
				<el-input
					v-model="editForm.value"
					:type="editForm.type === 'number' ? 'number' : 'text'"
					:placeholder="t('pages.toolbar.envDialog.valuePlaceholder')"
					clearable
				/>
			</el-form-item>
		</el-form>

		<template #footer>
			<div class="flex justify-end gap-8px">
				<el-button @click="cancelEdit">{{ t('common.cancel') }}</el-button>
				<el-button type="primary" @click="saveEdit">{{ t('common.save') }}</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { Icon } from '@repo/ui'
import type { FormInstance, FormRules } from 'element-plus'

import { useI18n } from '@/composables/useI18n'

interface AgentEnvVar {
	name: string
	value: string
	type: 'string' | 'number' | 'boolean' | 'object' | 'array'
}

const props = defineProps<{
	modelValue: boolean
	value?: AgentEnvVar[]
}>()

const emit = defineEmits<{
	(e: 'update:modelValue', value: boolean): void
	(e: 'change', value: AgentEnvVar[]): void
}>()

const { t } = useI18n()

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

const defaultItem: AgentEnvVar = {
	name: '',
	type: 'string',
	value: ''
}

const envList = ref<AgentEnvVar[]>([])
const editVisible = ref(false)
const editingIndex = ref(-1)
const editForm = reactive<AgentEnvVar>({ ...defaultItem })
const editFormRef = ref<FormInstance>()

const editFormRules = computed<FormRules<AgentEnvVar>>(() => ({
	name: [
		{
			required: true,
			trigger: 'blur',
			validator: (_rule, value: string, callback) => {
				const normalized = value?.trim()
				if (!normalized) {
					callback(new Error(t('pages.toolbar.envDialog.nameRequired')))
					return
				}

				const isDuplicate = envList.value.some(
					(item, index) => item.name === normalized && index !== editingIndex.value
				)
				if (isDuplicate) {
					callback(new Error(t('pages.toolbar.envDialog.nameDuplicate')))
					return
				}

				callback()
			}
		}
	],
	type: [
		{
			required: true,
			message: t('pages.toolbar.envDialog.typeRequired'),
			trigger: 'blur'
		}
	],
	value: [
		{
			required: true,
			message: t('pages.toolbar.envDialog.valueRequired'),
			trigger: 'blur'
		}
	]
}))

watch(
	() => props.value,
	(value) => {
		if (Array.isArray(value) && value.length > 0) {
			envList.value = value.map((item) => ({
				name: item.name,
				type: item.type,
				value: item.value ?? ''
			}))
			return
		}

		envList.value = []
	},
	{ immediate: true, deep: false }
)

function resetEditForm() {
	editForm.name = ''
	editForm.type = 'string'
	editForm.value = ''
	editFormRef.value?.clearValidate()
}

function onAddClick() {
	editingIndex.value = -1
	resetEditForm()
	editVisible.value = true
}

function onEditClick(index: number) {
	const target = envList.value[index]
	editingIndex.value = index
	editForm.name = target?.name ?? ''
	editForm.type = target?.type ?? 'string'
	editForm.value = target?.value ?? ''
	editVisible.value = true
}

function cancelEdit() {
	editVisible.value = false
	resetEditForm()
}

async function saveEdit() {
	if (!editFormRef.value) return

	const isValid = await editFormRef.value.validate().catch(() => false)
	if (!isValid) return

	const normalized: AgentEnvVar = {
		name: editForm.name.trim(),
		type: editForm.type,
		value: editForm.value ?? ''
	}

	if (!normalized.name) {
		editVisible.value = false
		return
	}

	if (editingIndex.value === -1) {
		envList.value.push({ ...normalized })
	} else if (envList.value[editingIndex.value]) {
		envList.value[editingIndex.value] = { ...normalized }
	}

	emit('change', envList.value)
	editVisible.value = false
	resetEditForm()
}

function removeEnv(index: number) {
	envList.value.splice(index, 1)
	emit('change', envList.value)
}
</script>

<style scoped>
.env-item-card:hover {
	border-color: #e5e7eb;
}
</style>
