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

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

import {
  ElAlert,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  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.condition.label'),
);
const branches = ref<any[]>(props.data.branches || []);

const operators = [
  {
    label: $t('ai-platform.workflow.panels.condition.equals'),
    value: 'equals',
    group: 'compare',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.notEquals'),
    value: 'not_equals',
    group: 'compare',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.gt'),
    value: 'gt',
    group: 'number',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.gte'),
    value: 'gte',
    group: 'number',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.lt'),
    value: 'lt',
    group: 'number',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.lte'),
    value: 'lte',
    group: 'number',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.contains'),
    value: 'contains',
    group: 'string',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.notContains'),
    value: 'not_contains',
    group: 'string',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.startsWith'),
    value: 'starts_with',
    group: 'string',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.endsWith'),
    value: 'ends_with',
    group: 'string',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.isEmpty'),
    value: 'is_empty',
    group: 'empty',
  },
  {
    label: $t('ai-platform.workflow.panels.condition.isNotEmpty'),
    value: 'is_not_empty',
    group: 'empty',
  },
];

if (branches.value.length === 0) {
  branches.value.push({
    id: `branch-${Date.now()}`,
    name: `${$t('ai-platform.workflow.panels.condition.branch', { index: 1 })}`,
    conditions: [],
  });
}

watch(
  [label, branches],
  ([labelVal, branchesVal]) => {
    emit('update', { ...props.data, label: labelVal, branches: branchesVal });
  },
  { deep: true },
);

const addBranch = () => {
  branches.value.push({
    id: `branch-${Date.now()}`,
    name: `${$t('ai-platform.workflow.panels.condition.branch', { index: branches.value.length + 1 })}`,
    conditions: [],
  });
};

const removeBranch = (index: number) => {
  branches.value.splice(index, 1);
};

const addCondition = (branchIndex: number) => {
  if (!branches.value[branchIndex].conditions) {
    branches.value[branchIndex].conditions = [];
  }
  branches.value[branchIndex].conditions.push({
    variable: '',
    operator: 'contains',
    value: '',
  });
};

const removeCondition = (branchIndex: number, conditionIndex: number) => {
  branches.value[branchIndex].conditions.splice(conditionIndex, 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.condition.placeholder')"
      />
    </ElFormItem>

    <!-- 使用提示 -->
    <ElAlert type="info" :closable="false" show-icon>
      <template #title>
        <span class="text-xs font-medium">{{
          $t('ai-platform.workflow.panels.common.usageTips')
        }}</span>
      </template>
      <ul class="mt-1 list-inside list-disc text-xs">
        <li>
          <b>{{ $t('ai-platform.workflow.panels.condition.booleanHint') }}</b>: <code class="bg-muted rounded px-1">true</code> /
          <code class="bg-muted rounded px-1">false</code>
        </li>
        <li>
          <b>{{
            $t('ai-platform.workflow.panels.condition.emptyStringHint')
          }}</b>: <code class="bg-muted rounded px-1">is_empty</code> /
          <code class="bg-muted rounded px-1">is_not_empty</code>
        </li>
        <li>
          <b>{{ $t('ai-platform.workflow.panels.condition.mainAppHint') }}</b>:
          <code class="bg-muted rounded px-1" v-pre>{{
            start.application_id
          }}</code>
          == <code class="bg-muted rounded px-1">main</code>
        </li>
        <li>
          <b>{{
            $t('ai-platform.workflow.panels.condition.numberCompareHint')
          }}</b>: {{ $t('ai-platform.workflow.panels.condition.numberCompare') }}
        </li>
      </ul>
    </ElAlert>

    <div class="flex items-center justify-between">
      <span class="text-foreground text-sm font-medium">{{
        $t('ai-platform.workflow.panels.condition.branchList')
      }}</span>
      <ElButton link type="primary" :icon="Plus" @click="addBranch">
        {{ $t('ai-platform.workflow.panels.condition.addBranch') }}
      </ElButton>
    </div>

    <div class="space-y-3">
      <div
        v-for="(branch, index) in branches"
        :key="branch.id"
        class="border-border bg-muted relative rounded border p-3"
      >
        <div class="mb-2 flex items-center justify-between">
          <span class="text-xs font-bold text-blue-600"
            >IF {{ index + 1 }}</span
          >
          <ElButton
            v-if="branches.length > 1"
            link
            type="danger"
            :icon="Trash2"
            @click="removeBranch(index)"
          />
        </div>
        <ElInput
          v-model="branch.name"
          :placeholder="$t('ai-platform.workflow.panels.parallel.branchName')"
          size="small"
          class="mb-2"
        />

        <!-- Conditions -->
        <div class="border-border mt-3 space-y-2 border-t pt-2">
          <div class="flex items-center justify-between">
            <span class="text-muted-foreground text-[10px] font-medium">{{
              $t('ai-platform.workflow.panels.condition.conditions')
            }}</span>
            <ElButton
              size="small"
              link
              type="primary"
              :icon="Plus"
              class="!text-[10px]"
              @click="addCondition(index)"
            >
              {{ $t('ai-platform.workflow.panels.common.addCondition') }}
            </ElButton>
          </div>

          <div
            v-if="!branch.conditions || branch.conditions.length === 0"
            class="text-muted-foreground text-center text-[10px]"
          >
            {{ $t('ai-platform.workflow.panels.condition.noCondition') }}
          </div>

          <div
            v-for="(cond, cIdx) in branch.conditions"
            :key="cIdx"
            class="flex flex-col gap-2 rounded border bg-white p-2 shadow-sm"
          >
            <div class="flex gap-2">
              <SmartInput
                v-model="cond.variable"
                :current-node-id="nodeId"
                :placeholder="$t('ai-platform.workflow.panels.common.variable')"
                size="small"
                class="flex-1"
              />
              <ElButton
                link
                type="danger"
                :icon="X"
                @click="removeCondition(index, cIdx as number)"
              />
            </div>

            <div class="flex gap-2">
              <ElSelect
                v-model="cond.operator"
                size="small"
                style="width: 100px; flex-shrink: 0"
              >
                <ElOption
                  v-for="op in operators"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value"
                />
              </ElSelect>

              <SmartInput
                v-if="!['is_empty', 'is_not_empty'].includes(cond.operator)"
                v-model="cond.value"
                :current-node-id="nodeId"
                :placeholder="$t('ai-platform.workflow.panels.common.value')"
                size="small"
                class="flex-1"
              />
            </div>
          </div>
        </div>
      </div>

      <div
        class="border-border bg-muted text-muted-foreground rounded border p-3 text-center text-xs"
      >
        {{ $t('ai-platform.workflow.panels.condition.elseBranch') }}
      </div>
    </div>
  </ElForm>
</template>
