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

import { EasyFlowFormModal } from '@easyflow/common-ui';

import { CircleCheckFilled, WarningFilled } from '@element-plus/icons-vue';
import {
  ElForm,
  ElFormItem,
  ElMessage,
  ElOption,
  ElSelect,
} from 'element-plus';

import { getModelList, verifyModelConfig } from '#/api/ai/llm';
import { $t } from '#/locales';
import { resolveModelVerificationFeedback } from '#/views/ai/model/modelUtils/model-verification';

type VerifyStatus = 'error' | 'idle' | 'success' | 'warning';

const options = ref<any[]>([]);
const modelType = ref('');
const vectorDimension = ref('');
const verifyStatus = ref<VerifyStatus>('idle');
const verifyMessage = ref('');
const formDataRef = ref();
const dialogVisible = ref(false);
const btnLoading = ref(false);

const formData = reactive({
  llmId: '',
});

const resultTitle = computed(() => {
  if (verifyStatus.value === 'success') {
    return '验证成功';
  }

  if (verifyStatus.value === 'error') {
    return '验证失败';
  }

  if (verifyStatus.value === 'warning') {
    return '流式不可用';
  }

  return '等待验证';
});

const getLlmList = async (providerId: string) => {
  const res = await getModelList({ providerId });
  if (res.errorCode === 0) {
    options.value = res.data;
  }
};

defineExpose({
  async openDialog(providerId: string) {
    formDataRef.value?.resetFields();
    formData.llmId = '';
    modelType.value = '';
    vectorDimension.value = '';
    verifyStatus.value = 'idle';
    verifyMessage.value = '请选择一个模型并开始验证。';
    await getLlmList(providerId);
    dialogVisible.value = true;
  },
});

const rules = {
  llmId: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'change',
    },
  ],
};

const getModelInfo = (id: string) => {
  const current = options.value.find((item: any) => item.id === id);
  modelType.value = current?.modelType || '';
  vectorDimension.value = '';
  verifyStatus.value = 'idle';
  verifyMessage.value = '已更新待验证模型，点击确认开始检测配置。';
};

const save = async () => {
  btnLoading.value = true;
  verifyStatus.value = 'idle';
  verifyMessage.value = '正在连接模型服务，请稍候...';

  try {
    await formDataRef.value.validate();
    const res = await verifyModelConfig(formData.llmId);

    if (res.errorCode === 0) {
      const feedback = resolveModelVerificationFeedback(res, modelType.value);
      verifyStatus.value = feedback.status;
      verifyMessage.value = feedback.message;
      if (feedback.status === 'warning') {
        ElMessage.warning(feedback.message);
      } else if (feedback.status === 'success') {
        ElMessage.success(feedback.message);
      } else {
        ElMessage.error(feedback.message);
      }
      if (modelType.value === 'embeddingModel' && feedback.dimension) {
        vectorDimension.value = String(feedback.dimension);
      }
    } else {
      verifyStatus.value = 'error';
      verifyMessage.value =
        res.message || $t('ui.actionMessage.operationFailed');
      ElMessage.error(verifyMessage.value);
    }
  } catch (error: any) {
    if (error?.fields) {
      verifyMessage.value = '请选择一个模型并开始验证。';
      return;
    }

    verifyStatus.value = 'error';
    verifyMessage.value =
      error?.message || $t('ui.actionMessage.operationFailed');
  } finally {
    btnLoading.value = false;
  }
};
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :centered="true"
    :closable="!btnLoading"
    :title="$t('llm.verifyLlmTitle')"
    width="560"
    :confirm-loading="btnLoading"
    :confirm-text="$t('button.confirm')"
    :submitting="btnLoading"
    @confirm="save"
  >
    <div class="verify-modal">
      <section class="verify-modal__section">
        <div class="verify-modal__section-head">
          <h3>1. 选择待验证模型</h3>
          <p>会用当前保存的配置检查基础连接和流式响应。</p>
        </div>

        <ElForm
          ref="formDataRef"
          :model="formData"
          status-icon
          :rules="rules"
          label-position="top"
          class="verify-modal__form"
        >
          <ElFormItem prop="llmId" :label="$t('llm.modelToBeTested')">
            <ElSelect
              v-model="formData.llmId"
              filterable
              placeholder="选择一个模型"
              @change="getModelInfo"
            >
              <ElOption
                v-for="item in options"
                :key="item.id"
                :label="item.title"
                :value="item.id || ''"
              />
            </ElSelect>
          </ElFormItem>
        </ElForm>
      </section>

      <section class="verify-modal__section verify-modal__section--result">
        <div class="verify-modal__section-head">
          <h3>2. 查看验证结果</h3>
          <p>会展示可用状态；向量模型还会展示向量维度。</p>
        </div>

        <div
          class="verify-result-card"
          :class="{
            'is-success': verifyStatus === 'success',
            'is-warning': verifyStatus === 'warning',
            'is-error': verifyStatus === 'error',
          }"
        >
          <div class="verify-result-card__icon">
            <CircleCheckFilled v-if="verifyStatus === 'success'" />
            <WarningFilled v-else />
          </div>
          <div class="verify-result-card__content">
            <h4>{{ resultTitle }}</h4>
            <p>{{ verifyMessage }}</p>
            <div
              v-if="modelType === 'embeddingModel' && vectorDimension"
              class="verify-result-card__meta"
            >
              向量维度：{{ vectorDimension }}
            </div>
          </div>
        </div>
      </section>
    </div>
  </EasyFlowFormModal>
</template>

<style scoped>
.verify-modal {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.verify-modal__section {
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 20px;
  background: linear-gradient(
    180deg,
    hsl(var(--surface-panel) / 98%) 0%,
    hsl(var(--surface-contrast-soft) / 94%) 100%
  );
  border: 1px solid hsl(var(--divider-faint) / 50%);
  border-radius: 24px;
}

.verify-modal__section-head h3,
.verify-result-card__content h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: hsl(var(--text-strong));
}

.verify-modal__section-head p,
.verify-result-card__content p,
.verify-result-card__meta {
  margin: 6px 0 0;
  font-size: 13px;
  line-height: 1.6;
  color: hsl(var(--text-muted));
}

.verify-result-card {
  display: flex;
  gap: 14px;
  align-items: flex-start;
  padding: 18px;
  background: hsl(var(--surface-panel) / 90%);
  border: 1px solid hsl(var(--divider-faint) / 56%);
  border-radius: 20px;
}

.verify-result-card.is-success {
  background: hsl(var(--success) / 6%);
  border-color: hsl(var(--success) / 36%);
}

.verify-result-card.is-warning {
  background: hsl(var(--warning) / 6%);
  border-color: hsl(var(--warning) / 36%);
}

.verify-result-card.is-error {
  background: hsl(var(--destructive) / 5%);
  border-color: hsl(var(--destructive) / 36%);
}

.verify-result-card__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  font-size: 18px;
  color: hsl(var(--text-strong));
  background: hsl(var(--surface-contrast-soft));
  border-radius: 999px;
}
</style>
