<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { Plus, Trash2 } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElAlert,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElSelect,
} from 'element-plus';

import SmartInput from '../components/SmartInput.vue';

const props = defineProps<{ data: any; nodeId: string }>();
const emit = defineEmits(['update']);

const label = ref(
  props.data.label || $t('ai-platform.workflow.panels.loop.label'),
);
const loopMode = ref(props.data.loop_mode || 'for_each');
const itemsVariable = ref(props.data.items_variable || '');
const itemVariableName = ref(props.data.item_variable_name || 'item');
const indexVariableName = ref(props.data.index_variable_name || 'index');
const maxIterations = ref(props.data.max_iterations || 100);
const outputVariable = ref(props.data.output_variable || 'loop_results');
const conditionLogic = ref(props.data.condition_logic || 'and');
const conditions = ref<any[]>(props.data.conditions || []);

// 操作符选项
const operatorOptions = [
  { value: 'eq', label: $t('ai-platform.workflow.panels.loop.eq') },
  { value: 'ne', label: $t('ai-platform.workflow.panels.loop.ne') },
  { value: 'gt', label: $t('ai-platform.workflow.panels.loop.gt') },
  { value: 'gte', label: $t('ai-platform.workflow.panels.loop.gte') },
  { value: 'lt', label: $t('ai-platform.workflow.panels.loop.lt') },
  { value: 'lte', label: $t('ai-platform.workflow.panels.loop.lte') },
  { value: 'is_empty', label: $t('ai-platform.workflow.panels.loop.is_empty') },
  {
    value: 'is_not_empty',
    label: $t('ai-platform.workflow.panels.loop.is_not_empty'),
  },
  { value: 'is_true', label: $t('ai-platform.workflow.panels.loop.is_true') },
  { value: 'is_false', label: $t('ai-platform.workflow.panels.loop.is_false') },
];

// 是否显示条件配置
const showConditions = computed(() => loopMode.value === 'while');

watch(
  [
    label,
    loopMode,
    itemsVariable,
    itemVariableName,
    indexVariableName,
    maxIterations,
    outputVariable,
    conditionLogic,
    conditions,
  ],
  ([
    labelVal,
    modeVal,
    itemsVal,
    itemNameVal,
    indexNameVal,
    maxVal,
    outputVal,
    logicVal,
    conditionsVal,
  ]) => {
    emit('update', {
      ...props.data,
      label: labelVal,
      loop_mode: modeVal,
      items_variable: itemsVal,
      item_variable_name: itemNameVal,
      index_variable_name: indexNameVal,
      max_iterations: maxVal,
      output_variable: outputVal,
      condition_logic: logicVal,
      conditions: conditionsVal,
    });
  },
  { deep: true },
);

const addCondition = () => {
  conditions.value.push({
    variable: '',
    operator: 'eq',
    value: '',
  });
};

const removeCondition = (index: number) => {
  conditions.value.splice(index, 1);
};
</script>

<template>
  <ElForm label-position="top" size="small" class="space-y-4">
    <ElFormItem :label="$t('ai-platform.workflow.panels.common.nodeName')">
      <ElInput
        v-model="label"
        :placeholder="$t('ai-platform.workflow.panels.loop.placeholder')"
      />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.loop.loopMode')">
      <ElSelect v-model="loopMode" class="w-full">
        <ElOption
          value="for_each"
          :label="$t('ai-platform.workflow.panels.loop.forEach')"
        />
        <ElOption
          value="while"
          :label="$t('ai-platform.workflow.panels.loop.whileLoop')"
        />
      </ElSelect>
    </ElFormItem>

    <!-- For Each 模式配置 -->
    <template v-if="loopMode === 'for_each'">
      <div>
        <label class="text-foreground mb-1 block text-sm font-medium">{{
          $t('ai-platform.workflow.panels.loop.arrayVariable')
        }}</label>
        <SmartInput
          v-model="itemsVariable"
          :current-node-id="nodeId"
          placeholder="e.g. {{start.items}} or [1, 2, 3]"
        />
        <div class="text-muted-foreground mt-1 text-xs">
          {{ $t('ai-platform.workflow.panels.loop.arrayVarHint') }}
        </div>
      </div>

      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="text-foreground mb-1 block text-sm font-medium">{{
            $t('ai-platform.workflow.panels.loop.itemVarName')
          }}</label>
          <ElInput v-model="itemVariableName" placeholder="item" />
        </div>
        <div>
          <label class="text-foreground mb-1 block text-sm font-medium">{{
            $t('ai-platform.workflow.panels.loop.indexVarName')
          }}</label>
          <ElInput v-model="indexVariableName" placeholder="index" />
        </div>
      </div>
    </template>

    <!-- While 模式配置 -->
    <template v-if="showConditions">
      <div class="flex items-center justify-between">
        <span class="text-foreground text-sm font-medium">{{
          $t('ai-platform.workflow.panels.loop.loopCondition')
        }}</span>
        <ElButton link type="primary" :icon="Plus" @click="addCondition">
          {{ $t('ai-platform.workflow.panels.common.addCondition') }}
        </ElButton>
      </div>

      <div v-if="conditions.length > 1">
        <label class="text-foreground mb-1 block text-sm font-medium">{{
          $t('ai-platform.workflow.panels.loop.conditionLogic')
        }}</label>
        <ElSelect v-model="conditionLogic" class="w-full">
          <ElOption
            value="and"
            :label="$t('ai-platform.workflow.panels.loop.allMatch')"
          />
          <ElOption
            value="or"
            :label="$t('ai-platform.workflow.panels.loop.anyMatch')"
          />
        </ElSelect>
      </div>

      <div class="space-y-2">
        <div
          v-for="(condition, index) in conditions"
          :key="index"
          class="rounded border border-green-200 bg-green-50 p-3"
        >
          <div class="mb-2 flex items-center justify-between">
            <span class="text-xs font-bold text-green-600">{{
              $t('ai-platform.workflow.panels.loop.conditionIndex', {
                index: index + 1,
              })
            }}</span>
            <ElButton
              link
              type="danger"
              :icon="Trash2"
              size="small"
              @click="removeCondition(index)"
            />
          </div>
          <div class="space-y-2">
            <SmartInput
              v-model="condition.variable"
              :current-node-id="nodeId"
              :placeholder="
                $t('ai-platform.workflow.panels.loop.varPlaceholder')
              "
              size="small"
            />
            <ElSelect v-model="condition.operator" size="small" class="w-full">
              <ElOption
                v-for="op in operatorOptions"
                :key="op.value"
                :value="op.value"
                :label="op.label"
              />
            </ElSelect>
            <SmartInput
              v-if="
                !['is_empty', 'is_not_empty', 'is_true', 'is_false'].includes(
                  condition.operator,
                )
              "
              v-model="condition.value"
              :current-node-id="nodeId"
              :placeholder="$t('ai-platform.workflow.panels.loop.compareValue')"
              size="small"
            />
          </div>
        </div>
      </div>

      <div
        v-if="conditions.length === 0"
        class="border-muted-foreground/30 text-muted-foreground rounded border border-dashed p-4 text-center text-sm"
      >
        {{ $t('ai-platform.workflow.panels.loop.addConditionHint') }}
      </div>
    </template>

    <div>
      <label class="text-foreground mb-1 block text-sm font-medium">{{
        $t('ai-platform.workflow.panels.loop.maxIterations')
      }}</label>
      <ElInputNumber
        v-model="maxIterations"
        :min="1"
        :max="10000"
        class="w-full"
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.loop.maxIterationsHint') }}
      </div>
    </div>

    <div>
      <label class="text-foreground mb-1 block text-sm font-medium">{{
        $t('ai-platform.workflow.panels.common.outputVarName')
      }}</label>
      <ElInput v-model="outputVariable" placeholder="loop_results" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.loop.outputVarHint') }}
      </div>
    </div>

    <ElAlert type="info" :closable="false" show-icon>
      <template #title>
        <span class="text-xs font-medium">{{
          $t('ai-platform.workflow.panels.common.usage')
        }}</span>
      </template>
      <ul class="mt-1 list-inside list-disc text-xs">
        <li>{{ $t('ai-platform.workflow.panels.loop.usageTip1') }}</li>
        <li>{{ $t('ai-platform.workflow.panels.loop.usageTip2') }}</li>
        <li v-if="loopMode === 'for_each'">
          {{ $t('ai-platform.workflow.panels.loop.loopBodyHint1') }}
          &#123;&#123;{{ itemVariableName }}&#125;&#125;
          {{ $t('ai-platform.workflow.panels.loop.loopBodyHint2') }}
          &#123;&#123;{{ indexVariableName }}&#125;&#125;
        </li>
        <li v-else>
          {{ $t('ai-platform.workflow.panels.loop.usageTip3While') }}
        </li>
        <li>
          {{
            $t('ai-platform.workflow.panels.loop.usageTip4', {
              output: outputTemplate,
            })
          }}
        </li>
      </ul>
    </ElAlert>
  </ElForm>
</template>
