import { computed, ref, watch, type Ref } from 'vue'
import { listSimpleFields } from '@/api/simpleField'
import type { SimpleFieldCategory, SimpleFieldRecord } from '@/types/simpleField'

export function fieldCategoryForMapKind(kind: 'site' | 'track' | 'car' | null): SimpleFieldCategory | null {
  if (kind === 'site') return 'siteFields'
  if (kind === 'track') return 'trackFields'
  if (kind === 'car') return 'carFields'
  return null
}

/** 按 key 去重（同 key 多条车型定义时保留第一条）。 */
function dedupeByKey(rows: SimpleFieldRecord[]): SimpleFieldRecord[] {
  const seen = new Set<string>()
  const out: SimpleFieldRecord[] = []
  for (const row of rows) {
    if (seen.has(row.key)) continue
    seen.add(row.key)
    out.push(row)
  }
  return out
}

function normalizeCarTypeToken(v: string | null | undefined): string {
  return (v ?? '').trim().replace(/^UI/i, '')
}

function shortCarType(v: string): string {
  const s = v.trim()
  const i = s.lastIndexOf('.')
  return i >= 0 ? s.slice(i + 1) : s
}

function filterRowsByCarType(rows: SimpleFieldRecord[], current: string | null | undefined): SimpleFieldRecord[] {
  const token = shortCarType(normalizeCarTypeToken(current)).toLowerCase()
  if (!token) return []
  return rows.filter((r) => shortCarType(r.carType).toLowerCase() === token)
}

export function useSimpleFieldCatalog(
  kind: Ref<'site' | 'track' | 'car' | null>,
  carType?: Ref<string | null | undefined>
) {
  const loading = ref(false)
  const records = ref<SimpleFieldRecord[]>([])

  const fieldType = computed(() => fieldCategoryForMapKind(kind.value))

  const byKey = computed(() => {
    const map = new Map<string, SimpleFieldRecord>()
    for (const row of records.value) map.set(row.key, row)
    return map
  })

  async function reload() {
    const ft = fieldType.value
    if (!ft) {
      records.value = []
      return
    }
    loading.value = true
    try {
      // 车辆：为兼容 shortName / assembly.shortName 等不同 car_type 存储格式，先拉 carFields 再前端匹配当前车型。
      if (ft === 'carFields') {
        const all = await listSimpleFields(ft)
        records.value = dedupeByKey(filterRowsByCarType(all, carType?.value))
      } else {
        const rows = await listSimpleFields(ft)
        records.value = dedupeByKey(rows)
      }
    } catch {
      records.value = []
    } finally {
      loading.value = false
    }
  }

  watch(fieldType, () => { void reload() }, { immediate: true })

  function labelForKey(key: string): string {
    const row = byKey.value.get(key)
    return row?.chinese?.trim() || row?.english?.trim() || '—'
  }

  function defaultValueForKey(key: string): string {
    return byKey.value.get(key)?.value ?? ''
  }

  return {
    loading,
    records,
    fieldType,
    byKey,
    reload,
    labelForKey,
    defaultValueForKey
  }
}
