import { computed } from 'vue'

import { useThemeSkin } from './useThemeSkin.js'

const DEFAULT_COLORS = {
  primary: '#3a7ca5',
  primaryActive: '#255b7d',
  primarySoft: '#eaf4fa',
  success: '#2f855a',
  warning: '#b7791f',
  danger: '#ef4444',
  info: '#475569',
  chartBlue: '#4f6f9f',
  chartPurple: '#6e7fa6',
  chartAmber: '#b58b4c'
}

function readCssVariable(name, fallback) {
  if (typeof window === 'undefined') {
    return fallback
  }

  const value = window.getComputedStyle(document.documentElement).getPropertyValue(name).trim()
  return value || fallback
}

export function resolveCssColor(value, fallback = DEFAULT_COLORS.primary) {
  if (typeof value !== 'string') {
    return fallback
  }

  const cssVariableMatch = value.match(/^var\((--[^,\s)]+)(?:,\s*([^)]+))?\)$/)
  if (!cssVariableMatch) {
    return value
  }

  return readCssVariable(cssVariableMatch[1], cssVariableMatch[2]?.trim() || fallback)
}

export function useThemeColors() {
  const { activeThemeSkinId } = useThemeSkin()

  return computed(() => {
    activeThemeSkinId.value

    const primary = readCssVariable('--theme-primary', DEFAULT_COLORS.primary)
    const primaryActive = readCssVariable('--theme-primary-active', DEFAULT_COLORS.primaryActive)

    return {
      primary,
      primaryActive,
      primarySoft: readCssVariable('--theme-primary-soft', DEFAULT_COLORS.primarySoft),
      success: readCssVariable('--success', DEFAULT_COLORS.success),
      warning: readCssVariable('--warning', DEFAULT_COLORS.warning),
      danger: readCssVariable('--danger', DEFAULT_COLORS.danger),
      info: readCssVariable('--info', DEFAULT_COLORS.info),
      chartPrimary: resolveCssColor(readCssVariable('--chart-primary', primary), primary),
      chartBlue: resolveCssColor(readCssVariable('--chart-blue', DEFAULT_COLORS.chartBlue), DEFAULT_COLORS.chartBlue),
      chartPurple: resolveCssColor(readCssVariable('--chart-purple', DEFAULT_COLORS.chartPurple), DEFAULT_COLORS.chartPurple),
      chartAmber: resolveCssColor(readCssVariable('--chart-amber', DEFAULT_COLORS.chartAmber), DEFAULT_COLORS.chartAmber),
      chartDanger: resolveCssColor(readCssVariable('--chart-danger', DEFAULT_COLORS.danger), DEFAULT_COLORS.danger)
    }
  })
}
