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

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

import {
  ElAlert,
  ElButton,
  ElCheckbox,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElRadioButton,
  ElRadioGroup,
  ElSelect,
  ElSlider,
  ElSwitch,
} from 'element-plus';

import { getActiveModelsApi } from '#/api/ai-platform/ai-platform';

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

interface SchemaField {
  name: string;
  type: string;
  description: string;
  required: boolean;
  items?: SchemaField;
  properties?: SchemaField[];
}

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

const form = ref({
  label: $t('ai-platform.workflow.panels.llm.label'),
  model_id: '',
  model_name: '',
  temperature: 0.7,
  system_prompt: '',
  user_prompt: '',
  max_tokens: 2048,
  top_p: 1,
  presence_penalty: 0,
  frequency_penalty: 0,
  json_mode: false,
  output_variable: 'llm_response',
  output_mode: 'text',
  output_schema: [] as SchemaField[],
  output_schema_source: 'static' as 'static' | 'variable', // 结构化输出来源：static 静态配置，variable 从变量获取
  output_schema_variable: '', // 结构化输出变量名
  use_streaming: false,
  use_conversation_history: false,
  ...props.data,
});

// Schema 配置 Dialog 显示状态
const schemaDialogVisible = ref(false);

// 打开 Schema 配置 Dialog
const openSchemaDialog = () => {
  schemaDialogVisible.value = true;
};

// Schema 配置确认
const handleSchemaConfirm = (schema: SchemaField[]) => {
  form.value.output_schema = schema;
};

// 计算 Schema 预览 JSON
const schemaPreviewJson = computed(() => {
  const buildSchema = (fields: SchemaField[]): any => {
    const properties: Record<string, any> = {};
    const required: string[] = [];

    for (const field of fields) {
      if (!field.name) continue;

      const prop: any = {
        type: field.type,
        description: field.description || undefined,
      };

      if (field.type === 'object' && field.properties) {
        const nested = buildSchema(field.properties);
        prop.properties = nested.properties;
        if (nested.required?.length > 0) {
          prop.required = nested.required;
        }
      } else if (field.type === 'array' && field.items) {
        if (field.items.type === 'object' && field.items.properties) {
          const nested = buildSchema(field.items.properties);
          prop.items = {
            type: 'object',
            properties: nested.properties,
          };
          if (nested.required?.length > 0) {
            prop.items.required = nested.required;
          }
        } else {
          prop.items = { type: field.items.type };
        }
      }

      properties[field.name] = prop;
      if (field.required) {
        required.push(field.name);
      }
    }

    return { properties, required };
  };

  if (form.value.output_schema.length === 0) {
    return '';
  }
  return JSON.stringify(buildSchema(form.value.output_schema), null, 2);
});

const models = ref<any[]>([]);

// 查找并更新模型名称
const updateModelName = (id: string) => {
  const model = models.value.find((m) => m.id === id);
  if (model) {
    form.value.model_name = model.model_name;
  }
};

onMounted(async () => {
  try {
    const res = await getActiveModelsApi();
    models.value = res.filter((m) => m.model_type === 'chat');
    // 如果有 model_id 但没有 model_name，尝试更新
    if (form.value.model_id && !form.value.model_name) {
      updateModelName(form.value.model_id);
    }
  } catch (error) {
    console.error(error);
  }
});

// 监听 model_id 变化
watch(
  () => form.value.model_id,
  (newId) => {
    updateModelName(newId);
  },
);

watch(
  form,
  (val) => {
    emit('update', val);
  },
  { deep: true },
);
</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.llm.placeholder')"
      />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.model')">
      <ElSelect
        v-model="form.model_id"
        :placeholder="$t('ai-platform.workflow.panels.common.selectModel')"
      >
        <ElOption
          v-for="m in models"
          :key="m.id"
          :label="m.model_name"
          :value="m.id"
        />
      </ElSelect>
    </ElFormItem>

    <ElFormItem>
      <template #label>
        <div class="flex items-center gap-2">
          <span>{{ $t('ai-platform.workflow.panels.llm.systemPrompt') }}</span>
          <span class="text-muted-foreground text-xs">{{
            $t('ai-platform.workflow.panels.llm.optional')
          }}</span>
        </div>
      </template>
      <SmartInput
        v-model="form.system_prompt"
        :current-node-id="nodeId"
        type="textarea"
        :rows="4"
        :placeholder="
          $t('ai-platform.workflow.panels.llm.systemPromptPlaceholder')
        "
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.llm.systemPromptHint') }}
      </div>
    </ElFormItem>

    <ElFormItem>
      <template #label>
        <div class="flex items-center gap-2">
          <span>{{ $t('ai-platform.workflow.panels.llm.userPrompt') }}</span>
          <span class="text-xs text-red-400">*</span>
        </div>
      </template>
      <SmartInput
        v-model="form.user_prompt"
        :current-node-id="nodeId"
        type="textarea"
        :rows="6"
        :placeholder="
          $t('ai-platform.workflow.panels.llm.userPromptPlaceholder')
        "
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.llm.userPromptHint') }}
      </div>
      <ElAlert type="info" :closable="false" show-icon class="mt-2">
        <template #title>
          <span class="text-xs">{{
            $t('ai-platform.workflow.panels.llm.ragTip')
          }}</span>
        </template>
      </ElAlert>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.outputVarName')">
      <ElInput v-model="form.output_variable" placeholder="llm_response" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.llm.outputVarHint') }}
      </div>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.llm.outputMode')">
      <ElRadioGroup v-model="form.output_mode">
        <ElRadioButton value="text">
          {{ $t('ai-platform.workflow.panels.llm.textOutput') }}
        </ElRadioButton>
        <ElRadioButton value="structured">
          {{ $t('ai-platform.workflow.panels.llm.structuredOutput') }}
        </ElRadioButton>
      </ElRadioGroup>
    </ElFormItem>
    <div class="text-muted-foreground mt-1 text-xs">
      {{
        form.output_mode === 'structured'
          ? $t('ai-platform.workflow.panels.llm.structuredDesc')
          : $t('ai-platform.workflow.panels.llm.textDesc')
      }}
    </div>
    <!-- 结构化输出字段定义 -->
    <template v-if="form.output_mode === 'structured'">
      <!-- 结构来源选择 -->
      <ElFormItem :label="$t('ai-platform.workflow.panels.llm.schemaSource')">
        <ElRadioGroup v-model="form.output_schema_source" size="small">
          <ElRadioButton value="static">
            {{ $t('ai-platform.workflow.panels.llm.staticConfig') }}
          </ElRadioButton>
          <ElRadioButton value="variable">
            {{ $t('ai-platform.workflow.panels.llm.fromVariable') }}
          </ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>
      <div class="text-muted-foreground mb-3 text-xs">
        {{
          form.output_schema_source === 'variable'
            ? $t('ai-platform.workflow.panels.llm.fromVariableDesc')
            : $t('ai-platform.workflow.panels.llm.staticConfigDesc')
        }}
      </div>

      <!-- 变量模式 -->
      <ElFormItem
        v-if="form.output_schema_source === 'variable'"
        :label="$t('ai-platform.workflow.panels.llm.schemaVariable')"
      >
        <SmartInput
          v-model="form.output_schema_variable"
          :current-node-id="nodeId"
          :placeholder="
            $t('ai-platform.workflow.panels.llm.schemaVarPlaceholder')
          "
        />
        <div class="text-muted-foreground mt-1 text-xs">
          {{ $t('ai-platform.workflow.panels.llm.schemaVarHint') }}
        </div>
      </ElFormItem>

      <!-- 静态配置模式 -->
      <ElFormItem v-else>
        <template #label>
          <div class="flex w-full items-center justify-between">
            <ElButton
              type="primary"
              link
              :icon="Settings"
              @click="openSchemaDialog"
            >
              {{ $t('ai-platform.workflow.panels.llm.configStructure') }}
            </ElButton>
          </div>
        </template>

        <div
          v-if="form.output_schema.length === 0"
          class="text-muted-foreground cursor-pointer rounded border border-dashed p-4 text-center text-xs hover:border-blue-400"
          @click="openSchemaDialog"
        >
          {{ $t('ai-platform.workflow.panels.llm.configSchemaHint') }}
        </div>

        <div v-else>
          <pre
            class="bg-muted/30 max-h-48 cursor-pointer overflow-auto rounded border p-3 text-xs hover:border-blue-400"
            @click="openSchemaDialog"
            >{{ schemaPreviewJson }}</pre
          >
          <div class="text-muted-foreground mt-2 text-xs">
            {{ $t('ai-platform.workflow.panels.llm.schemaPreviewHint') }}
            {{ form.output_variable }}
          </div>
        </div>
      </ElFormItem>
    </template>

    <!-- Schema 配置 Dialog -->
    <SchemaConfigDialog
      v-model="schemaDialogVisible"
      :schema="form.output_schema"
      @confirm="handleSchemaConfirm"
    />

    <!-- 高级设置分组 -->
    <div class="border-border rounded-lg border p-4">
      <div class="text-foreground mb-3 text-sm font-semibold">
        {{ $t('ai-platform.workflow.panels.common.advancedSettings') }}
      </div>

      <ElFormItem label="Temperature" class="!mb-3">
        <div class="flex items-center gap-4">
          <ElSlider
            v-model="form.temperature"
            :min="0"
            :max="1"
            :step="0.1"
            class="flex-1"
          />
          <ElInputNumber
            v-model="form.temperature"
            :min="0"
            :max="1"
            :step="0.1"
            size="small"
            style="width: 80px"
          />
        </div>
      </ElFormItem>

      <ElFormItem label="Max Tokens" class="!mb-3">
        <div class="flex items-center gap-4">
          <ElSlider
            v-model="form.max_tokens"
            :min="1"
            :max="4096"
            :step="1"
            class="flex-1"
          />
          <ElInputNumber
            v-model="form.max_tokens"
            :min="1"
            :max="4096"
            size="small"
            style="width: 80px"
          />
        </div>
      </ElFormItem>

      <ElFormItem label="Top P" class="!mb-3">
        <div class="flex items-center gap-4">
          <ElSlider
            v-model="form.top_p"
            :min="0"
            :max="1"
            :step="0.1"
            class="flex-1"
          />
          <ElInputNumber
            v-model="form.top_p"
            :min="0"
            :max="1"
            :step="0.1"
            size="small"
            style="width: 80px"
          />
        </div>
      </ElFormItem>

      <div class="flex items-center justify-between py-2">
        <span class="text-foreground text-sm font-medium">JSON Mode</span>
        <ElCheckbox v-model="form.json_mode" />
      </div>

      <div class="flex items-center justify-between py-2">
        <div>
          <div class="text-foreground text-sm font-medium">
            {{ $t('ai-platform.workflow.panels.llm.streaming') }}
          </div>
          <div class="text-muted-foreground text-xs">
            {{ $t('ai-platform.workflow.panels.llm.streamingHint') }}
          </div>
        </div>
        <ElSwitch v-model="form.use_streaming" />
      </div>

      <div class="flex items-center justify-between py-2">
        <div>
          <div class="text-foreground text-sm font-medium">
            {{ $t('ai-platform.workflow.panels.llm.conversationHistory') }}
          </div>
          <div class="text-muted-foreground text-xs">
            {{ $t('ai-platform.workflow.panels.llm.conversationHistoryHint') }}
          </div>
        </div>
        <ElSwitch v-model="form.use_conversation_history" />
      </div>
    </div>
  </ElForm>
</template>
