import type { ComposerResolveLocaleMessageTranslation } from 'vue-i18n'
import type { SolarIconVariant } from './useSolarIcon'

const log = createLogger('i18n')

function transformSolarIcon(value: string): string {
  const appConfig = useAppConfig()
  const targetVariant = appConfig.saas.ui!.solarIconVariant as SolarIconVariant

  if (!(value.startsWith('i-solar-') || value.startsWith('i-solar-'))) {
    return value
  }

  const solarPattern = /^(?:i-)?solar(?::|-)(.+)-(linear|bold|outline|broken|bold-duotone|line-duotone)$/
  const match = value.match(solarPattern)
  if (!match) return value

  const [, iconName, currentVariant] = match
  if (currentVariant === targetVariant) return value

  const isPrefixed = value.startsWith('i-solar-')
  return isPrefixed
    ? `i-solar-${iconName}-${targetVariant}`
    : `i-solar-${iconName}-${targetVariant}`
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function processItem(item: any, rt: ComposerResolveLocaleMessageTranslation<'nl' | 'en'>): any {
  const processedItem: Record<string, unknown> = {}

  for (const [entryKey, entryValue] of Object.entries(item as Record<string, unknown>)) {
    if (entryKey === 'children' && Array.isArray(entryValue)) {
      processedItem[entryKey] = entryValue.map(child => processItem(child, rt))
    } else if (typeof entryValue === 'boolean') {
      processedItem[entryKey] = entryValue
    } else if (entryKey === 'exact') {
      // Convert string "true"/"false" to boolean for exact property
      // If undefined, omit the property entirely
      if (entryValue !== undefined && entryValue !== null) {
        processedItem[entryKey] = String(entryValue) === 'true'
      }
    } else if (entryKey === 'icon') {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const translatedValue = String(rt(entryValue as any))
      processedItem[entryKey] = transformSolarIcon(translatedValue)
    } else {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      processedItem[entryKey] = String(rt(entryValue as any))
    }
  }
  return processedItem
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const useI18nMenus = <T>(key: string, tm: any, rt: ComposerResolveLocaleMessageTranslation<'nl' | 'en'>): T[][] => {
  const raw = tm(key) as unknown
  if (!Array.isArray(raw) || raw.length === 0) {
    log.warn('no groups found for key', key)
    return []
  }
  const groups = raw as T[][]
  return groups.map(group =>
    group.map((item: T) => processItem(item, rt) as T)
  )
}
