import copy from 'copy-to-clipboard'

import { kebabify } from '../../generate/utils'

export type ThemeValue = Record<'resolved' | 'alias', string | number>

export type Theme = Record<string, ThemeValue>

export type ColorsProps = {
  theme: Theme
}

import styles from './colors.module.css'

function getContrastColor(bgColor: string) {
  const r = parseInt(bgColor.substring(1, 3), 16)
  const g = parseInt(bgColor.substring(3, 5), 16)
  const b = parseInt(bgColor.substring(5, 7), 16)
  let a = parseInt(bgColor.substring(7, 9), 16)

  if (isNaN(a)) {
    a = 255
  }

  const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
  if (luminance > 0.5) {
    return '#000'
  } else {
    if (a < 255 / 2) {
      return '#000'
    }
    return '#fff'
  }
}

export function Colors({ theme }: ColorsProps) {
  const grouping: Record<string, Theme> = {}

  for (const [k, v] of Object.entries(theme)) {
    if (typeof v.resolved === 'string' && v.resolved.startsWith('#')) {
      const key = k.replace(/\/[^/]+$/, '')
      if (!grouping[key]) {
        grouping[key] = {}
      }

      grouping[key][k] = v
    }
  }

  return (
    <div className={styles.container}>
      <div className={styles.jumpTo}>
        <label>
          Jump to:
          <select
            onChange={(e) => {
              const el = document.getElementById(e.target.value)
              el?.scrollIntoView({
                behavior: 'smooth',
              })
            }}
          >
            <option>- Select a grouping -</option>
            {Object.keys(grouping)
              .sort((a, b) => a.localeCompare(b))
              .map((title) => {
                return (
                  <option key={title} value={kebabify(title)}>
                    {title}
                  </option>
                )
              })}
          </select>
        </label>
        <span className={styles.tip}>
          Click on any of the values to copy to clipboard!
        </span>
      </div>
      <div className={styles.groups}>
        {Object.entries(grouping)
          .sort((a, b) => {
            return a[0].localeCompare(b[0])
          })
          .map(([title, values]) => {
            return (
              <div className={styles.group} key={title}>
                <h2 id={kebabify(title)} className={styles.title}>
                  {title}
                </h2>
                <div className={styles.values}>
                  {Object.entries(values).map(([k, v]) => {
                    return (
                      <div className={styles.value} key={k}>
                        <div className={styles.colorContainer}>
                          <div
                            className={styles.color}
                            style={{
                              color: getContrastColor(v.resolved.toString()),
                              backgroundColor: v.resolved.toString(),
                            }}
                            onClick={() => {
                              copy(`var(--${kebabify(k)})`)
                            }}
                          >
                            var(--{kebabify(k)})
                          </div>
                        </div>
                        <div
                          className={styles.tokenName}
                          onClick={() => {
                            copy(k)
                          }}
                        >
                          Figma: {k}
                        </div>
                        <div
                          className={styles.tokenName}
                          onClick={() => {
                            copy(kebabify(k))
                          }}
                        >
                          CSS: {kebabify(k)}
                        </div>
                        {v.alias ? (
                          <div
                            className={styles.tokenAlias}
                            onClick={() => {
                              copy(v.alias.toString())
                            }}
                          >
                            Alias: {v.alias}
                          </div>
                        ) : null}
                        <div
                          className={styles.tokenValue}
                          onClick={() => {
                            copy(v.resolved.toString())
                          }}
                        >
                          Value: {v.resolved}
                        </div>
                      </div>
                    )
                  })}
                </div>
              </div>
            )
          })}
      </div>
    </div>
  )
}
