<template>
	<div class="w-full flex relative">
		<div class="left-0 top-0 w-[60px] relative" v-if="modelValue.length > 1">
			<div
				class="absolute bottom-4 left-[46px] top-4 w-2.5 rounded-l-[8px] border border-0.5px border-solid border-r-0 border-gray-500"
			></div>
			<div class="absolute right-0 top-1/2 h-[29px] w-4 -translate-y-1/2 bg-#fff"></div>
			<div
				class="absolute right-1 top-1/2 flex h-[21px] -translate-y-1/2 cursor-pointer select-none items-center rounded-md border-solid border-[0.5px] border-gray-200 px-1 text-[10px] font-semibold shadow-xs"
				@click="toggleOperator"
			>
				{{ modelOperator === 'and' ? 'AND' : 'OR' }}
				<Icon icon="lucide:refresh-ccw" />
			</div>
		</div>
		<div class="flex-1 flex flex-col gap-2">
			<template v-for="(_item, index) in modelValue">
				<div class="flex items-start gap-2">
					<ConditionItem v-model="modelValue[index]!" class="flex-1" />
					<IconButton link icon="lucide:trash-2" square @click="removeCondition(index)" />
				</div>
			</template>
		</div>
	</div>
	<div class="my-2" :style="{ marginLeft: modelValue.length > 1 ? '60px' : '0' }">
		<el-button size="small" @click="addCondition">
			{{ t('common.nodeBase.condition.addCondition') }}
		</el-button>
	</div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Icon, IconButton } from '@repo/ui'
import ConditionItem from './ConditionItem.vue'
import { useI18n } from '@/composables/useI18n'

import type { ConditionType } from '../../Interface'

const props = defineProps<{
	conditions: ConditionType[]
	operator: 'and' | 'or'
}>()

const emit = defineEmits<{
	(e: 'update:conditions', value: ConditionType[]): void
	(e: 'update:operator', value: 'and' | 'or'): void
}>()
const { t } = useI18n()

const modelValue = ref<ConditionType[]>(props.conditions)
const modelOperator = ref<'and' | 'or'>(props.operator)

const addCondition = () => {
	modelValue.value.push({
		left_value: '',
		right_value: '',
		comparison_operator: 'contains',
		varType: 'string'
	})
}

watch(
	modelValue,
	(val) => {
		emit('update:conditions', val)
	},
	{ deep: true }
)

watch(modelOperator, (val) => {
	emit('update:operator', val)
})

const removeCondition = (index: number) => {
	modelValue.value.splice(index, 1)
}

const toggleOperator = () => {
	modelOperator.value = modelOperator.value === 'and' ? 'or' : 'and'
}
</script>
