import { computed } from 'vue'

import {
  ENABLED_STATE_OPTIONS,
  ONLINE_STATE_OPTIONS,
  RISK_SCENARIO_OPTIONS,
  STATUS_OPTIONS
} from './auditViewMetadata.js'
import { RISK_RULE_LEVEL_OPTIONS } from './auditViewRiskRuleModel.js'
import {
  normalizeText,
  resolveDomainLabel,
  resolveStatusMeta
} from './auditViewModel.js'
import { filterAuditAssets } from './auditViewRuntimeModel.js'

function buildOptions(items, valueGetter, labelGetter, defaultLabel) {
  const values = []
  const seen = new Set()

  items.forEach((item) => {
    const value = normalizeText(valueGetter(item))
    if (!value || seen.has(value)) {
      return
    }
    seen.add(value)
    values.push(value)
  })

  return [
    { value: '', label: defaultLabel },
    ...values.map((value) => ({
      value,
      label: labelGetter(value)
    }))
  ]
}

export function useAuditListFilters({
  activeType,
  activeTabLabel,
  currentAssets,
  keyword,
  selectedDomain,
  selectedOwner,
  selectedRiskLevel,
  selectedStatus,
  selectedRiskScenario,
  selectedOnlineState,
  selectedEnabledState
}) {
  const showRiskScenarioFilter = computed(() =>
    ['financialRules', 'riskRules'].includes(activeType.value)
  )
  const showOwnerFilter = computed(() => activeType.value !== 'riskRules')
  const showRiskLevelFilter = computed(() => activeType.value === 'riskRules')
  const showStatusFilter = computed(() => true)
  const showOnlineFilter = computed(() => false)
  const showEnabledFilter = computed(() => false)

  const domainOptions = computed(() =>
    buildOptions(
      currentAssets.value,
      (item) => item.domainValue,
      (value) => resolveDomainLabel(value),
      '全部业务域'
    )
  )
  const ownerOptions = computed(() =>
    buildOptions(
      currentAssets.value,
      (item) => item.owner,
      (value) => value,
      '全部负责人'
    )
  )
  const riskLevelOptions = computed(() => [
    { value: '', label: '全部风险等级' },
    ...RISK_RULE_LEVEL_OPTIONS
  ])

  const selectedDomainLabel = computed(
    () => domainOptions.value.find((item) => item.value === selectedDomain.value)?.label || '业务域'
  )
  const selectedOwnerLabel = computed(
    () =>
      ownerOptions.value.find((item) => item.value === selectedOwner.value)?.label ||
      '负责人'
  )
  const selectedRiskLevelLabel = computed(
    () =>
      riskLevelOptions.value.find((item) => item.value === selectedRiskLevel.value)?.label ||
      '风险等级'
  )
  const selectedStatusLabel = computed(
    () => STATUS_OPTIONS.find((item) => item.value === selectedStatus.value)?.label || '状态'
  )
  const selectedRiskScenarioLabel = computed(
    () =>
      RISK_SCENARIO_OPTIONS.find((item) => item.value === selectedRiskScenario.value)?.label ||
      '使用场景'
  )
  const selectedOnlineStateLabel = computed(
    () =>
      ONLINE_STATE_OPTIONS.find((item) => item.value === selectedOnlineState.value)?.label ||
      '是否上线'
  )
  const selectedEnabledStateLabel = computed(
    () =>
      ENABLED_STATE_OPTIONS.find((item) => item.value === selectedEnabledState.value)?.label ||
      '是否启用'
  )

  const activeFilterTokens = computed(() => {
    const tokens = []

    if (selectedDomain.value) {
      tokens.push(`业务域：${resolveDomainLabel(selectedDomain.value)}`)
    }
    if (showRiskScenarioFilter.value && selectedRiskScenario.value) {
      tokens.push(`使用场景：${selectedRiskScenario.value}`)
    }
    if (showStatusFilter.value && selectedStatus.value) {
      tokens.push(`状态：${resolveStatusMeta(selectedStatus.value).label}`)
    }
    if (showOnlineFilter.value && selectedOnlineState.value) {
      tokens.push(`是否上线：${selectedOnlineStateLabel.value}`)
    }
    if (showEnabledFilter.value && selectedEnabledState.value) {
      tokens.push(`是否启用：${selectedEnabledStateLabel.value}`)
    }
    if (showOwnerFilter.value && selectedOwner.value) {
      tokens.push(`负责人：${selectedOwner.value}`)
    }
    if (showRiskLevelFilter.value && selectedRiskLevel.value) {
      tokens.push(`风险等级：${selectedRiskLevelLabel.value}`)
    }
    if (keyword.value.trim()) {
      tokens.push(`搜索：${keyword.value.trim()}`)
    }

    return tokens
  })

  const visibleSkills = computed(() =>
    filterAuditAssets(currentAssets.value, {
      keyword: keyword.value,
      selectedDomain: selectedDomain.value,
      selectedOwner: selectedOwner.value,
      selectedRiskLevel: selectedRiskLevel.value,
      selectedStatus: selectedStatus.value,
      selectedRiskScenario: selectedRiskScenario.value,
      selectedOnlineState: selectedOnlineState.value,
      selectedEnabledState: selectedEnabledState.value,
      showStatusFilter: showStatusFilter.value,
      showRiskScenarioFilter: showRiskScenarioFilter.value,
      showOnlineFilter: showOnlineFilter.value,
      showEnabledFilter: showEnabledFilter.value
    })
  )

  const auditEmptyState = computed(() => {
    const hasFilters = activeFilterTokens.value.length > 0
    const supportedFilters = [
      '业务域',
      ...(showOwnerFilter.value ? ['负责人'] : []),
      ...(showRiskLevelFilter.value ? ['风险等级'] : []),
      ...(showRiskScenarioFilter.value ? ['使用场景'] : []),
      ...(showStatusFilter.value ? ['状态'] : []),
      ...(showOnlineFilter.value ? ['是否上线'] : []),
      ...(showEnabledFilter.value ? ['是否启用'] : []),
      '关键词'
    ]

    if (!currentAssets.value.length) {
      return {
        eyebrow: `${activeTabLabel.value}资产`,
        title: `${activeTabLabel.value}列表暂时还是空的`,
        desc: `当前环境里还没有可展示的${activeTabLabel.value}资产。完成接入或同步后，会统一展示在这里。`,
        icon: 'mdi mdi-database-search-outline',
        actionLabel: '',
        actionIcon: '',
        tone: 'amber',
        artLabel: 'ASSET',
        tips: [
          '切换页签可查看其他资产类型',
          `支持按${supportedFilters.slice(0, -1).join('、')}和关键词做过滤`
        ]
      }
    }

    return {
      eyebrow: '筛选结果为空',
      title: `没有找到匹配的${activeTabLabel.value}`,
      desc: hasFilters
        ? `试试清空${supportedFilters.join('、')}筛选，再重新查看。`
        : `当前列表中还没有满足展示条件的${activeTabLabel.value}资产。`,
      icon: hasFilters ? 'mdi mdi-tune-variant' : 'mdi mdi-view-grid-outline',
      actionLabel: hasFilters ? '清空筛选' : '',
      actionIcon: hasFilters ? 'mdi mdi-filter-remove-outline' : '',
      tone: hasFilters ? 'primary' : 'slate',
      artLabel: hasFilters ? 'FILTER' : 'QUEUE',
      tips: hasFilters
        ? [
            `${supportedFilters.join('、')}会叠加过滤`,
            showRiskScenarioFilter.value
              ? '可以换个规则名称或场景分类继续搜索'
              : '可以换个编码、名称或负责人关键词继续搜索'
          ]
        : ['列表展示来自真实资产 API', '切换资产类型后会自动重新拉取数据']
    }
  })

  return {
    activeFilterTokens,
    auditEmptyState,
    domainOptions,
    ownerOptions,
    riskLevelOptions,
    selectedDomainLabel,
    selectedEnabledStateLabel,
    selectedOnlineStateLabel,
    selectedOwnerLabel,
    selectedRiskLevelLabel,
    selectedRiskScenarioLabel,
    selectedStatusLabel,
    showEnabledFilter,
    showOnlineFilter,
    showOwnerFilter,
    showRiskLevelFilter,
    showRiskScenarioFilter,
    showStatusFilter,
    visibleSkills
  }
}
