import { computed, type ComputedRef } from 'vue'
import type { Composer } from 'vue-i18n'
import type { FeaturePolicyFieldDef, FeaturePolicyModel } from '../types'
import { FeaturePolicySections, parseFeaturePolicyJson } from '../types'

export interface FeatureStrategyRow {
  name: string
  valueText: string
  isEnabled: boolean
  conditionsText: string
}

/**
 * 功能策略表格数据生成 composable
 * @param t i18n 实例
 * @param i18nPrefix 国际化 key 前缀（如 'tenantPackage.detail.featureStrategy'）
 * @param jsonValue 功能策略 JSON 字符串（响应式）
 */
export function useFeatureStrategyTable(
  t: Composer['t'],
  i18nPrefix: string,
  jsonValue: ComputedRef<string>
) {
  // 1. 构建 label key 映射表
  const featurePolicyLabelKeyMap = new Map<string, string>(
    FeaturePolicySections.flatMap((section) =>
      section.fields.map((field) => [field.key, field.labelKey] as const)
    )
  )

  // 2. 解析结果
  const parseResult = computed(() => parseFeaturePolicyJson(jsonValue.value || ''))
  const isValidJson = computed(() => parseResult.value.isValidJson)

  // 3. 辅助函数
  const resolvePolicyLabel = (key: string) => {
    const labelKey = featurePolicyLabelKeyMap.get(key)
    return labelKey ? t(labelKey) : t(`${i18nPrefix}.conditions.unknownDependency`, { key })
  }

  const getPolicyValue = (model: FeaturePolicyModel, keyPath: string): unknown => {
    const [group, ...rest] = keyPath.split('.')
    const fieldKey = rest.join('.')

    if (group === 'features') return model.features?.[fieldKey]
    if (group === 'quotas') return model.quotas?.[fieldKey]
    return undefined
  }

  const formatPolicyValue = (field: FeaturePolicyFieldDef, model: FeaturePolicyModel): string => {
    const raw = getPolicyValue(model, field.key)

    if (field.type === 'boolean') {
      return raw ? t('common.yes') : t('common.no')
    }

    if (field.type === 'number') {
      return typeof raw === 'number' ? String(raw) : t(`${i18nPrefix}.value.unlimited`)
    }

    return raw === null || raw === undefined ? '' : String(raw)
  }

  const buildPolicyConditions = (field: FeaturePolicyFieldDef): string => {
    const parts: string[] = []

    if (field.dependsOnKey) {
      parts.push(
        t(`${i18nPrefix}.conditions.dependsOnEnabled`, {
          name: resolvePolicyLabel(field.dependsOnKey)
        })
      )
    }

    if (typeof field.min === 'number') {
      parts.push(t(`${i18nPrefix}.conditions.min`, { min: field.min }))
    }

    if (typeof field.max === 'number') {
      parts.push(t(`${i18nPrefix}.conditions.max`, { max: field.max }))
    }

    return parts.length ? parts.join('；') : t(`${i18nPrefix}.noConditions`)
  }

  const buildFeatureStrategyRow = (
    field: FeaturePolicyFieldDef,
    model: FeaturePolicyModel
  ): FeatureStrategyRow => {
    const dependsOk = field.dependsOnKey ? !!getPolicyValue(model, field.dependsOnKey) : true
    const raw = getPolicyValue(model, field.key)
    const isEnabled = field.type === 'boolean' ? !!raw : dependsOk

    return {
      name: t(field.labelKey),
      valueText: formatPolicyValue(field, model),
      isEnabled,
      conditionsText: buildPolicyConditions(field)
    }
  }

  // 4. 生成表格行数据
  const rows = computed<FeatureStrategyRow[]>(() => {
    const model = parseResult.value.model
    return FeaturePolicySections.flatMap((section) =>
      section.fields.map((field) => buildFeatureStrategyRow(field, model))
    )
  })

  return {
    rows,
    isValidJson,
    parseResult
  }
}
