import { defineComponent } from 'vue'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { ModelConfig, ProviderOption, ModelCreate, ModelType } from '@/shared/types'
import { modelApi } from '@/core/api'
import { watch } from 'vue'

export default defineComponent({
  name: 'ModelSettingsView',
  setup() {
    const router = useRouter()
    
    // 状态
    const loading = ref(false)
    const submitting = ref(false)
    const deleting = ref(false)
    const showAddDialog = ref(false)
    const deleteDialogVisible = ref(false)
    const modelToDelete = ref<ModelConfig | null>(null)
    const models = ref<ModelConfig[]>([])
    
    // 表单
    const modelForm = reactive<ModelCreate>({
      provider: 'minimax',
      model_type: 'chat',
      model_name: '',
      api_key: '',
      api_base: 'https://api.minimax.chat/v1',
      is_default: false
    })
    
    // 供应商默认 API 地址
    const providerDefaultUrls: Record<string, string> = {
      minimax: 'https://api.minimax.chat/v1',
      glm: 'https://open.bigmodel.cn/api/paas/v4',
      openai: 'https://api.openai.com/v1',
      ali: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
    }
    
    type ProviderOptionItem = ProviderOption & {
      desc: string
    }
    
    type ModelTypeOption = {
      value: ModelType
      label: string
      abbr: string
      desc: string
    }
    
    // 提供商
    const providers: ProviderOptionItem[] = [
      { value: 'minimax', label: 'MiniMax', abbr: 'MM', desc: '适合国内接入，默认官方端点' },
      { value: 'glm', label: 'GLM', abbr: 'GL', desc: '智谱接口，兼容常见模型配置' },
      { value: 'openai', label: 'OpenAI Compatible', abbr: 'OP', desc: '适配 OpenAI 及兼容协议服务' },
      { value: 'ali', label: '阿里云百炼', abbr: 'AL', desc: '默认走 DashScope 兼容模式端点' }
    ]
    
    const modelTypes: ModelTypeOption[] = [
      { value: 'chat', label: 'Chat', abbr: 'CH', desc: '标准对话生成模型' },
      { value: 'vlm', label: 'VLM', abbr: 'VL', desc: '视觉语言模型，适合图文输入' },
      { value: 'embedding', label: 'Embedding', abbr: 'EM', desc: '文本向量化与语义检索' },
      { value: 'rerank', label: 'Rerank', abbr: 'RR', desc: '重排模型，用于检索结果排序' }
    ]
    
    const normalizeModelType = (modelType?: string, modelName?: string): ModelType => {
      if (modelType && modelTypes.some(type => type.value === modelType) && modelType !== 'chat') {
        return modelType as ModelType
      }
    
      const normalizedName = (modelName || '').trim().toLowerCase()
    
      if (['rerank', 'bce-reranker', 'gte-rerank'].some(keyword => normalizedName.includes(keyword))) {
        return 'rerank'
      }
    
      if (
        [
          'embedding',
          'embed',
          'text-embedding',
          'bge-',
          'bge_m3',
          'gte-',
          'm3e',
          'e5-',
          'jina-embeddings'
        ].some(keyword => normalizedName.includes(keyword))
      ) {
        return 'embedding'
      }
    
      if (['vl', 'vision', 'visual', 'multimodal', 'qwen-vl', 'gpt-4o'].some(keyword => normalizedName.includes(keyword))) {
        return 'vlm'
      }
    
      return 'chat'
    }
    
    // 监听 provider 变化，自动设置默认 API 地址
    
    watch(() => modelForm.provider, (newProvider) => {
      if (providerDefaultUrls[newProvider]) {
        modelForm.api_base = providerDefaultUrls[newProvider]
      }
    })
    
    // 方法
    const goHome = () => router.push('/')
    
    const getProviderAbbr = (provider: string) => {
      const p = providers.find(p => p.value === provider)
      return p?.abbr || '?'
    }
    
    const getModelTypeLabel = (modelType?: string, modelName?: string) => {
      const item = modelTypes.find(type => type.value === normalizeModelType(modelType, modelName))
      return item?.label || 'Chat'
    }
    
    const fetchModels = async () => {
      loading.value = true
      try {
        const res = await modelApi.list()
        // Handle different response formats
        if (Array.isArray(res)) {
          models.value = res.map(model => ({
            ...model,
            model_type: normalizeModelType(model.model_type, model.model_name)
          }))
        } else if (res?.data && Array.isArray(res.data)) {
          models.value = res.data.map((model: ModelConfig) => ({
            ...model,
            model_type: normalizeModelType(model.model_type, model.model_name)
          }))
        } else {
          models.value = []
        }
      } catch (error: any) {
        console.error('获取模型列表失败:', error)
        ElMessage.error(error?.message || '加载失败')
      } finally {
        loading.value = false
      }
    }
    
    const openAddDialog = () => {
      modelForm.provider = 'minimax'
      modelForm.model_type = 'chat'
      modelForm.model_name = ''
      modelForm.api_key = ''
      modelForm.api_base = providerDefaultUrls['minimax']
      modelForm.is_default = false
      showAddDialog.value = true
    }
    
    const addModel = async () => {
      if (!modelForm.model_name || !modelForm.api_key) {
        ElMessage.warning('请填写模型名称和 API Key')
        return
      }
    
      submitting.value = true
      try {
        // Convert is_default from boolean to string
        const data = {
          provider: modelForm.provider,
          model_type: modelForm.model_type,
          model_name: modelForm.model_name,
          api_key: modelForm.api_key,
          api_base: modelForm.api_base,
          is_default: modelForm.is_default ? 'true' : 'false'
        }
        await modelApi.create(data)
        ElMessage.success('添加成功')
        showAddDialog.value = false
        fetchModels()
      } catch (error: any) {
        console.error('添加模型失败:', error)
        ElMessage.error(error?.message || '添加失败')
      } finally {
        submitting.value = false
      }
    }
    
    const confirmDelete = (model: ModelConfig) => {
      modelToDelete.value = model
      deleteDialogVisible.value = true
    }
    
    const handleDelete = async () => {
      if (!modelToDelete.value?.id) return
      deleting.value = true
      try {
        await modelApi.delete(modelToDelete.value.id)
        ElMessage.success('删除成功')
        deleteDialogVisible.value = false
        modelToDelete.value = null
        fetchModels()
      } catch (error: any) {
        console.error('删除模型失败:', error)
        ElMessage.error(error?.message || '删除失败')
      } finally {
        deleting.value = false
      }
    }
    
    const testConnection = async (model: ModelConfig) => {
      ElMessage.info(`正在测试 ${model.model_name}...`)
      try {
        const res = await modelApi.test(model.id)
        // Update model connection status from response
        const modelItem = models.value.find(m => m.id === model.id)
        if (modelItem && res?.model) {
          modelItem.connection_status = res.model.connection_status
          if (res.test_result?.success) {
            ElMessage.success('连接成功！')
          } else {
            ElMessage.error(res.test_result?.message || '连接失败')
          }
        }
      } catch (error: any) {
        console.error('测试连接失败:', error)
        const modelItem = models.value.find(m => m.id === model.id)
        if (modelItem) {
          modelItem.connection_status = 'disconnected'
        }
        ElMessage.error(error?.message || '连接失败')
      }
    }
    
    onMounted(() => fetchModels())

    return {
      router,
      loading,
      submitting,
      deleting,
      showAddDialog,
      deleteDialogVisible,
      modelToDelete,
      models,
      modelForm,
      providerDefaultUrls,
      providers,
      modelTypes,
      normalizeModelType,
      goHome,
      getProviderAbbr,
      getModelTypeLabel,
      fetchModels,
      openAddDialog,
      addModel,
      confirmDelete,
      handleDelete,
      testConnection
    }
  }
})
