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

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

import { ArrowDown, ArrowUp } from '@element-plus/icons-vue';
import {
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElMessage,
  ElOption,
  ElSelect,
} from 'element-plus';

import { api } from '#/api/request';
import UploadAvatar from '#/components/upload/UploadAvatar.vue';
import { $t } from '#/locales';
import { syncProgrammaticFieldValidation } from '#/utils/form-validation';
import ModelProviderBadge from '#/views/ai/model/ModelProviderBadge.vue';
import {
  getProviderPresetByValue,
  providerPresets,
} from '#/views/ai/model/modelUtils/defaultIcon';

const emit = defineEmits(['reload']);

const formDataRef = ref();
const dialogVisible = ref(false);
const btnLoading = ref(false);
const isAdd = ref(true);
const showAdvanced = ref(false);

const formData = reactive({
  id: '',
  icon: '',
  providerName: '',
  providerType: '',
  apiKey: '',
  endpoint: '',
  chatPath: '',
  embedPath: '',
  rerankPath: '',
});

const selectedPreset = computed(() =>
  getProviderPresetByValue(formData.providerType),
);

const hasLegacyProvider = computed(
  () => !selectedPreset.value && !!formData.providerType,
);

const getModeLabel = (mode?: 'hosted' | 'self-hosted') =>
  mode === 'self-hosted' ? '自部署' : '云服务';

const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    icon: '',
    providerName: '',
    providerType: '',
    apiKey: '',
    endpoint: '',
    chatPath: '',
    embedPath: '',
    rerankPath: '',
  });
};

defineExpose({
  openAddDialog() {
    isAdd.value = true;
    dialogVisible.value = true;
    showAdvanced.value = false;
    formDataRef.value?.resetFields();
    resetFormData();
  },
  openEditDialog(item: any) {
    isAdd.value = false;
    dialogVisible.value = true;
    showAdvanced.value = false;
    formDataRef.value?.clearValidate();
    resetFormData();
    Object.assign(formData, {
      ...item,
      icon: item.icon || '',
      providerName: item.providerName || '',
      providerType: item.providerType || '',
      apiKey: item.apiKey || '',
      endpoint: item.endpoint || '',
      chatPath: item.chatPath || '',
      embedPath: item.embedPath || '',
      rerankPath: item.rerankPath || '',
    });
  },
});

const closeDialog = () => {
  dialogVisible.value = false;
};

const rules = {
  providerName: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'blur',
    },
  ],
  providerType: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'change',
    },
  ],
  endpoint: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'blur',
    },
  ],
  chatPath: [
    {
      required: true,
      message: $t('message.required'),
      trigger: 'blur',
    },
  ],
};

const applyPreset = (value: string) => {
  const preset = getProviderPresetByValue(value);
  if (!preset) {
    return;
  }

  formData.providerType = preset.value;
  formData.providerName = preset.label;
  formData.endpoint = preset.options.llmEndpoint || '';
  formData.chatPath = preset.options.chatPath || '';
  formData.embedPath = preset.options.embedPath || '';
  formData.rerankPath = preset.options.rerankPath || '';
  syncProgrammaticFieldValidation(formDataRef, [
    'providerType',
    'providerName',
    'endpoint',
    'chatPath',
    'embedPath',
    'rerankPath',
  ]);
};

const save = async () => {
  btnLoading.value = true;

  try {
    await formDataRef.value.validate();

    const url = isAdd.value
      ? '/api/v1/modelProvider/save'
      : '/api/v1/modelProvider/update';
    const res = await api.post(url, formData);

    if (res.errorCode === 0) {
      ElMessage.success(res.message || '服务商已保存');
      emit('reload');
      closeDialog();
    } else {
      ElMessage.error(res.message || $t('ui.actionMessage.operationFailed'));
    }
  } catch (error) {
    if (!(error as any)?.fields) {
      ElMessage.error($t('ui.actionMessage.operationFailed'));
    }
  } finally {
    btnLoading.value = false;
  }
};
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :centered="true"
    :closable="!btnLoading"
    :title="isAdd ? '添加服务商' : '编辑服务商'"
    :before-close="closeDialog"
    width="680"
    :confirm-loading="btnLoading"
    :confirm-text="$t('button.save')"
    :submitting="btnLoading"
    @confirm="save"
  >
    <ElForm
      ref="formDataRef"
      :model="formData"
      status-icon
      :rules="rules"
      label-position="top"
      class="provider-modal"
    >
      <section class="provider-modal__section">
        <div class="provider-modal__section-head">
          <h3>服务商预设</h3>
          <p>先选择预设，系统会自动回填推荐网关与默认路径。</p>
        </div>

        <ElFormItem prop="providerType" :label="$t('llmProvider.apiType')">
          <ElSelect
            v-model="formData.providerType"
            filterable
            placeholder="选择一个服务商预设"
            popper-class="provider-preset-select-dropdown"
            @change="applyPreset"
          >
            <template #prefix>
              <ModelProviderBadge
                v-if="selectedPreset"
                :provider-name="selectedPreset.label"
                :provider-type="selectedPreset.value"
                :size="20"
              />
            </template>
            <ElOption
              v-for="item in providerPresets"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div class="provider-preset-option">
                <div class="provider-preset-option__meta">
                  <ModelProviderBadge
                    :provider-name="item.label"
                    :provider-type="item.value"
                    :size="24"
                  />
                  <strong>{{ item.label }}</strong>
                </div>
                <span>{{ getModeLabel(item.mode) }}</span>
              </div>
            </ElOption>
          </ElSelect>
        </ElFormItem>

        <div v-if="hasLegacyProvider" class="provider-modal__legacy">
          当前类型为
          {{
            formData.providerType
          }}，该类型不在最新预设列表中，但仍可继续编辑。
        </div>
      </section>

      <section class="provider-modal__section">
        <div class="provider-modal__section-head">
          <h3>基础接入</h3>
          <p>先完成主流程字段：名称、密钥、Endpoint、对话路径。</p>
        </div>

        <div class="provider-modal__grid">
          <ElFormItem
            prop="providerName"
            :label="$t('llmProvider.providerName')"
          >
            <ElInput
              v-model.trim="formData.providerName"
              placeholder="例如：OpenAI 生产环境"
            />
          </ElFormItem>
          <ElFormItem prop="apiKey" :label="$t('llmProvider.apiKey')">
            <ElInput
              v-model.trim="formData.apiKey"
              type="password"
              show-password
              placeholder="填写服务商密钥"
            />
          </ElFormItem>
        </div>

        <ElFormItem prop="endpoint" :label="$t('llmProvider.endpoint')">
          <ElInput
            v-model.trim="formData.endpoint"
            placeholder="填写网关地址"
          />
        </ElFormItem>

        <ElFormItem prop="chatPath" :label="$t('llmProvider.chatPath')">
          <ElInput
            v-model.trim="formData.chatPath"
            placeholder="对话模型请求路径"
          />
        </ElFormItem>
      </section>

      <section class="provider-modal__section">
        <button
          type="button"
          class="provider-modal__advanced-toggle"
          @click="showAdvanced = !showAdvanced"
        >
          <div>
            <h3>高级设置</h3>
            <p>包含向量/重排路径、图标上传和预设说明，默认收起。</p>
          </div>
          <ElIcon>
            <ArrowUp v-if="showAdvanced" />
            <ArrowDown v-else />
          </ElIcon>
        </button>

        <div v-if="showAdvanced" class="provider-modal__advanced">
          <div class="provider-modal__grid">
            <ElFormItem prop="embedPath" :label="$t('llmProvider.embedPath')">
              <ElInput
                v-model.trim="formData.embedPath"
                placeholder="向量模型请求路径"
              />
            </ElFormItem>
            <ElFormItem prop="rerankPath" :label="$t('llmProvider.rerankPath')">
              <ElInput
                v-model.trim="formData.rerankPath"
                placeholder="Rerank 请求路径"
              />
            </ElFormItem>
          </div>

          <div class="provider-modal__advanced-grid">
            <div class="provider-modal__icon-panel">
              <h4>图标上传</h4>
              <p>用于区分同一厂商在测试、预发、生产等不同环境。</p>
              <ElFormItem prop="icon" :label="$t('llmProvider.icon')">
                <UploadAvatar v-model="formData.icon" />
              </ElFormItem>
            </div>
          </div>
        </div>
      </section>
    </ElForm>
  </EasyFlowFormModal>
</template>

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

.provider-modal__section {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
  background: hsl(var(--surface-panel) / 92%);
  border: 1px solid hsl(var(--divider-faint) / 54%);
  border-radius: 14px;
}

.provider-modal__section-head h3,
.provider-modal__advanced-toggle h3,
.provider-modal__preset-head h4,
.provider-modal__icon-panel h4 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: hsl(var(--text-strong));
}

.provider-modal__section-head p,
.provider-modal__advanced-toggle p,
.provider-modal__legacy,
.provider-modal__preset-head p,
.provider-modal__icon-panel p {
  margin: 6px 0 0;
  font-size: 13px;
  line-height: 1.6;
  color: hsl(var(--text-muted));
}

.provider-preset-option {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
}

.provider-preset-option__meta {
  display: flex;
  gap: 10px;
  align-items: center;
}

.provider-preset-option strong {
  font-size: 14px;
  color: hsl(var(--text-strong));
}

.provider-preset-option span {
  padding: 4px 8px;
  font-size: 12px;
  color: hsl(var(--text-muted));
  background: hsl(var(--surface-contrast-soft));
  border-radius: 999px;
}

.provider-modal__legacy {
  padding: 10px 12px;
  background: hsl(var(--warning) / 7%);
  border: 1px solid hsl(var(--warning) / 26%);
  border-radius: 10px;
}

.provider-modal__grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.provider-modal__advanced-toggle {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0;
  text-align: left;
  background: transparent;
  border: none;
}

.provider-modal__advanced {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.provider-modal__advanced-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr);
  gap: 12px;
}

.provider-modal__icon-panel {
  padding: 12px;
  background: hsl(var(--surface-contrast-soft) / 70%);
  border: 1px solid hsl(var(--divider-faint) / 54%);
  border-radius: 12px;
}

@media (max-width: 760px) {
  .provider-modal__grid,
  .provider-modal__advanced-grid {
    grid-template-columns: minmax(0, 1fr);
  }
}
</style>
