import type { Color } from '@based/ui'
import tinycolor from 'tinycolor2'

export const handleClickOpenURL = (url: string) => {
  window.open(url, '_blank', 'noopener,noreferrer')
}

export const getFirstComponentBySection = (
  data: Record<string, any>,
  section: string,
  group: string,
): string => {
  const components = Object.values(data)
    .filter((item) => item.meta?.section === section)
    .filter((item) => {
      if (!item.meta?.group) {
        return true
      }

      return item.meta?.group.toLowerCase().includes(group.toLowerCase())
    })
    .sort((a, b) => a.meta.name.localeCompare(b.meta.name))

  return components.length > 0 && components[0].meta.id
}

export const getFirstComponentBySection2 = (
  meta: Based.UI.Extractor.MetaResult,
  section: string = 'components',
) => {
  const filteredEntries = Object.entries(meta).filter(
    ([_, value]) => value.meta.section === section,
  )

  const components = Object.keys(Object.fromEntries(filteredEntries))

  console.log(meta)

  return components[0]
}

export const parseSections = (input: Based.UI.Extractor.MetaResult) => {
  return Object.values(input).reduce(
    (acc, obj) => {
      const section = obj.meta.section

      if (section in acc) {
        acc[section as Based.UI.Playground.RouterParams['section']]++
      }

      return acc
    },
    {
      components: 0,
      colors: 0,
      typography: 0,
    },
  )
}

export const handleCopy = (content: string) =>
  navigator.clipboard.writeText(content)

export const getCssVariable = (variable: string) =>
  getComputedStyle(document.documentElement).getPropertyValue(variable).trim()

export const getColorVariables = (
  colors: Record<string, string>,
  name: string,
): Based.UI.Playground.Content.Color[] => {
  const regex = new RegExp(`^${name}\\d+`)
  const filteredEntries = Object.entries(colors)
    .filter(([key, _]) => regex.test(key))
    .map(([key, value]) => {
      const match = value.match(/^var\(--(.+)\)$/)
      return match ? ([key, `--${match[1]}`] as [string, string]) : null
    })
    .filter((entry): entry is [string, string] => entry !== null)
    .map(([key, value]) => {
      const css = getCssVariable(value)
      const color = tinycolor(css)

      return {
        name: key as Color,
        var: value,
        hex: color.toHex8String(),
        rgba: color.toRgbString(),
        hsl: color.toHslString(),
      }
    })

  return filteredEntries
}

export const scrollToDiv = (id: string) => {
  const element = document.getElementById(id)

  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

export const scrollToElement = (
  containerRef: React.RefObject<HTMLDivElement>,
  id: string,
  offset: number,
) => {
  const scrollableDiv = containerRef.current
  const targetElement = document.getElementById(id)

  if (scrollableDiv && targetElement) {
    const targetPosition =
      targetElement.offsetTop - scrollableDiv.offsetTop + offset

    scrollableDiv.scrollTo({
      top: targetPosition,
      behavior: 'smooth',
    })
  }
}
