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

import { Play } from '@vben/icons';
import { $t } from '@vben/locales';

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

const props = withDefaults(
  defineProps<{
    visible: boolean;
    nodes: any[];
    workflowName?: string;
  }>(),
  {
    workflowName: '',
  },
);

const emit = defineEmits<{
  (e: 'update:visible', val: boolean): void;
  (e: 'submit', inputs: Record<string, any>): void;
}>();

const inputs = ref<Record<string, any>>({});

const startNode = computed(() => props.nodes.find((n) => n.type === 'start'));
const variables = computed(() => startNode.value?.data?.variables || []);

watch(
  variables,
  (vars) => {
    const newInputs: Record<string, any> = {};
    vars.forEach((v: any) => {
      newInputs[v.variable] = inputs.value[v.variable] || v.default_value || '';
    });
    inputs.value = newInputs;
  },
  { immediate: true },
);

watch(
  () => props.visible,
  (val) => {
    if (!val) {
      inputs.value = {};
    }
  },
);

const handleRun = () => {
  emit('submit', { ...inputs.value });
  emit('update:visible', false);
};
</script>

<template>
  <ElDialog
    :model-value="props.visible"
    :title="workflowName || $t('ai-platform.workflow.editor.runPanel.runPreview')"
    :width="'480px'"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @update:model-value="emit('update:visible', $event)"
  >
    <div class="text-muted-foreground mb-3 text-xs font-semibold uppercase tracking-wider">
      {{ $t('ai-platform.workflow.editor.runPanel.inputVariables') }}
    </div>
    <ElForm label-position="top" size="default">
      <ElFormItem
        v-for="v in variables"
        :key="v.variable"
        :label="v.label || v.variable"
        :required="v.required"
      >
        <ElInput
          v-model="inputs[v.variable]"
          :placeholder="$t('ai-platform.workflow.editor.runPanel.inputPlaceholder', { type: v.type })"
          :type="v.type === 'number' ? 'number' : 'text'"
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="flex justify-center">
        <ElButton type="primary" :icon="Play" @click="handleRun">
          {{ $t('ai-platform.workflow.editor.runPanel.startRun') }}
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>
