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

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

import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElTooltip,
} from 'element-plus';

import { ZqDialog } from '#/components/zq-dialog';

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

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

const form = ref({
  label: $t('ai-platform.workflow.panels.code.label'),
  language: 'python3',
  code: '',
  timeout: 30,
  inputs: [] as any[],
  outputs: [] as any[],
  ...props.data,
});

if (!form.value.inputs) form.value.inputs = [];
if (!form.value.outputs) form.value.outputs = [];

// 默认代码模板
const defaultCode = `def main(inputs):
    # 在这里编写代码
    # inputs 包含所有上下文变量
    # 返回字典，result 字段将作为输出
    return {
        "result": "Hello " + inputs.get("name", "World")
    }`;

// 初始化默认代码
if (!form.value.code) {
  form.value.code = defaultCode;
}

watch(
  form,
  (val) => {
    emit('update', val);
  },
  { deep: true },
);

const addInput = () => {
  form.value.inputs.push({ variable: '', default_value: '' });
};

const removeInput = (index: number) => {
  form.value.inputs.splice(index, 1);
};

const addOutput = () => {
  form.value.outputs.push({ variable: '', type: 'string' });
};

const removeOutput = (index: number) => {
  form.value.outputs.splice(index, 1);
};

const codeEditorVisible = ref(false);
</script>

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

    <ElFormItem :label="$t('ai-platform.workflow.panels.code.timeout')">
      <ElInputNumber
        v-model="form.timeout"
        :min="1"
        :max="300"
        class="w-full"
      />
    </ElFormItem>

    <div class="border-border rounded-lg border p-4">
      <div class="mb-3 flex items-center justify-between">
        <span class="text-foreground text-xs">{{
          $t('ai-platform.workflow.panels.common.inputVars')
        }}</span>
        <ElButton link type="primary" :icon="Plus" @click="addInput">
          {{ $t('ai-platform.workflow.panels.common.add') }}
        </ElButton>
      </div>
      <div class="space-y-2">
        <div
          v-for="(item, index) in form.inputs"
          :key="index"
          class="flex gap-2"
        >
          <ElInput
            v-model="item.variable"
            :placeholder="$t('ai-platform.workflow.panels.common.variableName')"
            size="small"
            class="!w-28"
          />
          <SmartInput
            v-model="item.default_value"
            :current-node-id="nodeId"
            :placeholder="$t('ai-platform.workflow.panels.common.defaultValue')"
            size="small"
          />
          <ElButton
            link
            type="danger"
            :icon="Trash2"
            @click="removeInput(index)"
          />
        </div>
        <div
          v-if="form.inputs.length === 0"
          class="text-muted-foreground text-center text-xs"
        >
          {{ $t('ai-platform.workflow.panels.code.noInputVars') }}
        </div>
      </div>
    </div>

    <div class="border-border rounded-lg border p-4">
      <div class="mb-3 flex items-center justify-between">
        <span class="text-foreground text-xs">{{
          $t('ai-platform.workflow.panels.common.outputVars')
        }}</span>
        <ElButton link type="primary" :icon="Plus" @click="addOutput">
          {{ $t('ai-platform.workflow.panels.common.add') }}
        </ElButton>
      </div>
      <div class="space-y-2">
        <div
          v-for="(item, index) in form.outputs"
          :key="index"
          class="flex gap-2"
        >
          <ElInput
            v-model="item.variable"
            :placeholder="$t('ai-platform.workflow.panels.common.variableName')"
            size="small"
            class="!w-28"
          />
          <ElButton
            link
            type="danger"
            :icon="Trash2"
            @click="removeOutput(index)"
          />
        </div>
        <div
          v-if="form.outputs.length === 0"
          class="text-muted-foreground text-center text-xs"
        >
          {{ $t('ai-platform.workflow.panels.code.noOutputVars') }}
        </div>
      </div>
    </div>

    <div>
      <div class="mb-2 flex items-center justify-between">
        <span class="text-foreground text-xs">{{
          $t('ai-platform.workflow.panels.code.codePython')
        }}</span>
        <ElTooltip
          :content="$t('ai-platform.workflow.panels.code.expandEditor')"
        >
          <ElButton link type="primary" @click="codeEditorVisible = true">
            <Maximize2 class="size-4" />
          </ElButton>
        </ElTooltip>
      </div>
      <ElInput
        v-model="form.code"
        type="textarea"
        :rows="14"
        resize="vertical"
        class="workflow-code-textarea"
        :placeholder="$t('ai-platform.workflow.panels.code.codePlaceholder')"
      />
    </div>
  </ElForm>

  <ZqDialog
    v-model="codeEditorVisible"
    class="code-editor-dialog"
    :title="$t('ai-platform.workflow.panels.code.codePython')"
    width="960px"
    :show-footer="false"
  >
    <div class="code-editor-dialog-content">
      <ElInput
        v-model="form.code"
        type="textarea"
        resize="none"
        class="workflow-code-textarea workflow-code-textarea--dialog"
        :placeholder="$t('ai-platform.workflow.panels.code.codePlaceholder')"
      />
    </div>
  </ZqDialog>
</template>

<style>
/* 代码编辑器弹窗：内容区与编辑器占满 dialog（含全屏） */
.code-editor-dialog .zq-dialog-body .el-scrollbar,
.code-editor-dialog .zq-dialog-body .el-scrollbar__wrap,
.code-editor-dialog .zq-dialog-body .el-scrollbar__view,
.code-editor-dialog .zq-dialog-body .el-scrollbar__view > div,
.code-editor-dialog .code-editor-dialog-content {
  height: 100%;
}

.code-editor-dialog:not(.is-fullscreen) .zq-dialog-body {
  height: 70vh;
}

.code-editor-dialog:not(.is-fullscreen) .zq-dialog-body .el-scrollbar {
  height: 100%;
}

.code-editor-dialog .code-editor-dialog-content {
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.code-editor-dialog.is-fullscreen .el-dialog__body {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
}

.code-editor-dialog.is-fullscreen .zq-dialog-body {
  flex: 1;
  min-height: 0;
}

.code-editor-dialog.is-fullscreen .zq-dialog-body .el-scrollbar {
  height: 100% !important;
}

.workflow-code-textarea textarea {
  font-family:
    ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
    'Courier New', monospace;
  font-size: 12px;
  line-height: 1.6;
}

.workflow-code-textarea--dialog,
.workflow-code-textarea--dialog textarea {
  height: 100%;
}
</style>
