import { computed, reactive, ref } from 'vue'

export const RECEIPT_FILTER_ALL = 'all'

const QUALITY_OPTIONS = [
  { value: RECEIPT_FILTER_ALL, label: '全部置信度' },
  { value: 'high', label: '高置信度' },
  { value: 'medium', label: '中等置信度' },
  { value: 'low', label: '低置信度' },
  { value: 'missing', label: '待确认' }
]

function normalizeText(value) {
  return String(value ?? '').trim()
}

function getFilterValue(filters, key) {
  return normalizeText(filters?.[key]) || RECEIPT_FILTER_ALL
}

function buildUniqueOptions(rows, valueKey, labelKey, allLabel) {
  const seen = new Map()
  for (const row of Array.isArray(rows) ? rows : []) {
    const value = normalizeText(row?.[valueKey])
    if (!value || seen.has(value)) continue
    seen.set(value, normalizeText(row?.[labelKey]) || value)
  }

  return [
    { value: RECEIPT_FILTER_ALL, label: allLabel },
    ...Array.from(seen.entries())
      .map(([value, label]) => ({ value, label }))
      .sort((left, right) => left.label.localeCompare(right.label, 'zh-Hans-CN'))
  ]
}

function resolveReceiptMonth(row) {
  const raw = normalizeText(row?.document_date) || normalizeText(row?.uploaded_at)
  const match = raw.match(/^(\d{4})[-/年]?(\d{1,2})/)
  if (!match) return ''
  return `${match[1]}-${String(match[2]).padStart(2, '0')}`
}

function buildMonthOptions(rows) {
  const months = new Set((Array.isArray(rows) ? rows : []).map(resolveReceiptMonth).filter(Boolean))
  return [
    { value: RECEIPT_FILTER_ALL, label: '全部月份' },
    ...Array.from(months)
      .sort((left, right) => right.localeCompare(left))
      .map((value) => ({ value, label: `${value.replace('-', '年')}月` }))
  ]
}

function resolveScore(row) {
  const score = Number(row?.avg_score || 0)
  return Number.isFinite(score) ? score : 0
}

function matchesQuality(row, quality) {
  if (quality === RECEIPT_FILTER_ALL) return true
  const score = resolveScore(row)
  if (quality === 'missing') return score <= 0
  if (quality === 'high') return score >= 0.9
  if (quality === 'medium') return score >= 0.75 && score < 0.9
  if (quality === 'low') return score > 0 && score < 0.75
  return true
}

export function buildReceiptFilterControls(rows, filters) {
  return [
    {
      key: 'documentType',
      label: '票据类型',
      options: buildUniqueOptions(rows, 'document_type', 'document_type_label', '全部类型')
    },
    {
      key: 'scene',
      label: '费用场景',
      options: buildUniqueOptions(rows, 'scene_code', 'scene_label', '全部场景')
    },
    {
      key: 'month',
      label: '票据月份',
      options: buildMonthOptions(rows)
    },
    {
      key: 'quality',
      label: '置信度',
      options: QUALITY_OPTIONS
    }
  ].map((control) => ({
    ...control,
    value: getFilterValue(filters, control.key)
  }))
}

export function applyReceiptListFilters(rows, filters) {
  const documentType = getFilterValue(filters, 'documentType')
  const scene = getFilterValue(filters, 'scene')
  const month = getFilterValue(filters, 'month')
  const quality = getFilterValue(filters, 'quality')

  return (Array.isArray(rows) ? rows : []).filter((row) => (
    (documentType === RECEIPT_FILTER_ALL || normalizeText(row?.document_type) === documentType)
    && (scene === RECEIPT_FILTER_ALL || normalizeText(row?.scene_code) === scene)
    && (month === RECEIPT_FILTER_ALL || resolveReceiptMonth(row) === month)
    && matchesQuality(row, quality)
  ))
}

export function buildReceiptFilterTokens(controls, filters) {
  return (Array.isArray(controls) ? controls : [])
    .map((control) => {
      const value = getFilterValue(filters, control.key)
      if (value === RECEIPT_FILTER_ALL) return ''
      const option = control.options.find((item) => item.value === value)
      return `${control.label}：${option?.label || value}`
    })
    .filter(Boolean)
}

export function createReceiptFolderListFilterModel({ receipts, activeRows, keyword }) {
  const openReceiptFilterKey = ref('')
  const receiptFilters = reactive({
    documentType: RECEIPT_FILTER_ALL,
    scene: RECEIPT_FILTER_ALL,
    month: RECEIPT_FILTER_ALL,
    quality: RECEIPT_FILTER_ALL
  })
  const receiptFilterControls = computed(() => buildReceiptFilterControls(receipts.value, receiptFilters))
  const hasActiveReceiptFilters = computed(() => Object.values(receiptFilters).some((value) => value !== RECEIPT_FILTER_ALL))
  const filteredRows = computed(() => {
    const normalized = keyword.value.trim().toLowerCase()
    const filtered = applyReceiptListFilters(activeRows.value, receiptFilters)
    if (!normalized) return filtered
    return filtered.filter((item) => [
      item.file_name,
      item.document_type_label,
      item.scene_label,
      item.summary,
      item.amount,
      item.document_date,
      item.linked_claim_no
    ].filter(Boolean).join('').toLowerCase().includes(normalized))
  })

  function toggleReceiptFilter(key) {
    openReceiptFilterKey.value = openReceiptFilterKey.value === key ? '' : key
  }

  function selectReceiptFilter(key, value) {
    receiptFilters[key] = value
    openReceiptFilterKey.value = ''
  }

  function resolveReceiptFilterLabel(control) {
    return control.options.find((option) => option.value === receiptFilters[control.key])?.label || control.label
  }

  function clearReceiptFilters() {
    receiptFilters.documentType = RECEIPT_FILTER_ALL
    receiptFilters.scene = RECEIPT_FILTER_ALL
    receiptFilters.month = RECEIPT_FILTER_ALL
    receiptFilters.quality = RECEIPT_FILTER_ALL
    openReceiptFilterKey.value = ''
  }

  return {
    filteredRows,
    hasActiveReceiptFilters,
    openReceiptFilterKey,
    receiptFilterControls,
    receiptFilters,
    clearReceiptFilters,
    resolveReceiptFilterLabel,
    selectReceiptFilter,
    toggleReceiptFilter
  }
}
