import { Theme } from '@context-providers/theme-context-provider'
import type { CustomCell, CustomRenderer } from '@glideapps/glide-data-grid'

const cache: Record<string, string> = {}
export function cssVarToTableString(name: string, theme: Theme) {
  const themeName = `${theme}_${name}`

  if (!(themeName in cache) || cache[themeName] === '' || cache[themeName] === undefined) {
    let value = getComputedStyle(document.documentElement).getPropertyValue(name).trim()
    // Convert numeric font-weight to keyword if variable name suggests font-weight
    if (name.includes('font-weight')) {
      value = value === '700' ? 'bold' : 'normal'
    }

    cache[themeName] = value
  }
  return cache[themeName]
}

export const getTableTheme = (theme: Theme) => ({
  bgHeader: cssVarToTableString('--background', theme),
  bgHeaderHovered: cssVarToTableString('--background', theme),
  bgHeaderHasFocus: cssVarToTableString('--background', theme),
  bgCell: cssVarToTableString('--background', theme),
  accentColor: 'transparent',
  textHeaderSelected: cssVarToTableString('--foreground', theme),
  textGroupHeader: cssVarToTableString('--foreground', theme),
  textHeader: cssVarToTableString('--foreground', theme),
  textLight: cssVarToTableString('--background', theme),
  textDark: cssVarToTableString('--table-foreground', theme),
  textMedium: cssVarToTableString('--muted-foreground', theme),

  accentLight: cssVarToTableString('--background', theme),
  linkColor: cssVarToTableString('--primary', theme),
  drilldownBorder: cssVarToTableString('--background', theme),
  cellHorizontalPadding: 15,
  headerFontStyle: `${cssVarToTableString('--font-weight-bold', theme)} ${cssVarToTableString('--text-base', theme)}`,
  baseFontStyle: `${cssVarToTableString('--font-weight-medium', theme)} ${cssVarToTableString('--text-base', theme)}`,

  fontFamily: 'Helvetica, sans-serif',
})

export type HoverableRenderer<T extends CustomCell = CustomCell> = {
  hoverOverlay?: (cellData: T['data']) => React.ReactNode
} & CustomRenderer<T>

export function isHoverableRenderer(r: any): r is { hoverOverlay: (data: any) => React.ReactNode } {
  return typeof r?.hoverOverlay === 'function'
}
