<template>
	<div class="space-y-3">
		<div class="flex items-center justify-between beautify">
			<label class="text-14px font-bold text-gray-700">
				{{ t('common.nodeBase.inputVariables.title') }}
			</label>

			<el-tooltip :content="t('common.nodeBase.inputVariables.addVariable')">
				<IconButton
					link
					icon="lucide:plus"
					:height="16"
					:width="16"
					class="text-gray-600"
					@click="addVariable"
				/>
			</el-tooltip>
		</div>

		<div class="space-y-2">
			<div
				v-for="(variable, index) in variables"
				:key="index"
				class="flex items-center gap-2 group"
			>
				<el-input
					v-model="variable.name"
					:placeholder="t('common.nodeBase.inputVariables.variableNamePlaceholder')"
					class="flex-1/5 shrink-0 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
				/>
				<VarSelect
					v-model="variable.value"
					:placeholder="t('common.nodeBase.inputVariables.setValuePlaceholder')"
					@change="(variable) => handleVariableChange(variable, index)"
				/>

				<IconButton
					link
					icon="lucide:trash-2"
					class="text-red-500"
					@click="removeVariable(index)"
				/>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { IconButton } from '@repo/ui'
import VarSelect from './VarSelect.vue'
import { useI18n } from '@/composables/useI18n'
import type { NodeVariable } from '@/nodes/Interface'

interface Props {
	modelValue: NodeVariable[]
}

interface Emits {
	(e: 'update:modelValue', value: NodeVariable[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

const variables = ref<NodeVariable[]>(props.modelValue || [])

watch(
	() => props.modelValue,
	(newVal) => {
		variables.value = newVal || []
	}
)
// 添加变量
const addVariable = () => {
	const newVariable: NodeVariable = {
		name: '',
		type: 'string',
		value: ''
	}
	variables.value.push(newVariable)
}

// 删除变量
const removeVariable = (index: number) => {
	variables.value.splice(index, 1)
}

const handleVariableChange = (variable: { value: string; type: string }, index: number) => {
	if (variables.value?.[index]) {
		variables.value[index].type = variable.type as NodeVariable['type']
	}
}
</script>

<style lang="less" scoped>
.beautify {
	padding-bottom: 10px;
	border-bottom: 1px solid #eee;
}
</style>
