import { computed, ref, onMounted, onUnmounted } from 'vue'

const THEMES = {
  light: {
    text: '#6b7280',
    grid: 'rgba(0, 0, 0, 0.06)',
    title: '#374151',
    accentLine: '#111827',
  },
  dark: {
    text: '#9ca3af',
    grid: 'rgba(255, 255, 255, 0.08)',
    title: '#d1d5db',
    accentLine: '#e5e7eb',
  },
}

function readDarkMode() {
  return typeof document !== 'undefined'
    && document.documentElement.classList.contains('dark')
}

function prefersReducedMotion() {
  return typeof window !== 'undefined'
    && window.matchMedia('(prefers-reduced-motion: reduce)').matches
}

function useHtmlDarkMode() {
  const darkMode = ref(readDarkMode())
  let observer

  onMounted(() => {
    darkMode.value = readDarkMode()
    observer = new MutationObserver(() => {
      darkMode.value = readDarkMode()
    })
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
  })

  onUnmounted(() => observer?.disconnect())

  return darkMode
}

export function useChartTheme() {
  const darkMode = useHtmlDarkMode()
  const theme = computed(() => (darkMode.value ? THEMES.dark : THEMES.light))

  const animation = computed(() => ({
    duration: prefersReducedMotion() ? 0 : 400,
  }))

  const scaleDefaults = computed(() => ({
    ticks: { color: theme.value.text },
    grid: { color: theme.value.grid },
    title: { color: theme.value.title },
  }))

  const legendDefaults = computed(() => ({
    labels: {
      color: theme.value.text,
      boxWidth: 12,
      font: { size: 11 },
    },
  }))

  const accentLine = computed(() => theme.value.accentLine)

  function buildOptions(overrides = {}) {
    return computed(() => {
      const {
        tooltip: tooltipOverride,
        legend: legendOverride,
        ...restPlugins
      } = overrides.plugins ?? {}

      const base = {
        responsive: true,
        maintainAspectRatio: true,
        animation: animation.value,
        scales: {
          x: {
            ...scaleDefaults.value,
            ticks: { ...scaleDefaults.value.ticks, maxRotation: 45 },
            ...(overrides.scales?.x ?? {}),
          },
          y: {
            ...scaleDefaults.value,
            ...(overrides.scales?.y ?? {}),
          },
        },
        plugins: {
          legend: {
            display: false,
            ...legendDefaults.value,
            ...(legendOverride ?? {}),
          },
          tooltip: {
            padding: 12,
            boxPadding: 6,
            intersect: false,
            mode: 'nearest',
            titleFont: { size: 14 },
            bodyFont: { size: 14 },
            ...(tooltipOverride ?? {}),
          },
          ...restPlugins,
        },
        interaction: overrides.interaction ?? {
          mode: 'nearest',
          intersect: false,
          axis: 'x',
        },
      }

      if (overrides.scales?.count) {
        base.scales.count = {
          ...scaleDefaults.value,
          ...overrides.scales.count,
        }
      }
      if (overrides.scales?.criteria) {
        base.scales.criteria = overrides.scales.criteria
      }

      return base
    })
  }

  return {
    darkMode,
    theme,
    accentLine,
    scaleDefaults,
    legendDefaults,
    buildOptions,
  }
}
