import React, { useEffect, useState } from 'react'

import EmptyState from '../EmptyState/EmptyState'
import SearchBar from '../SearchBar/SearchBar'
import Tile from '../Tiles/Tile/Tile'
import { colorVariables } from './colors'

const ColorLookup = (): React.JSX.Element => {
  const [variableName, setVariableName] = useState<string>('')
  const [searchValue, setSearchValue] = useState<string>('')

  // Helper function to normalize the input
  const normalizeHexValue = (value: string): string => {
    return value.startsWith('#') ? value.slice(1) : value
  }

  useEffect(() => {
    // Function to get the value of a CSS variable
    const getCssVariableValue = (variableName: string): string => {
      const root = document.documentElement
      const computedStyle = getComputedStyle(root)
      return computedStyle.getPropertyValue(variableName).trim()
    }

    // Create a map of CSS variable values to their names
    const cssVariableMap: Record<string, string> = {}
    colorVariables.forEach((variable) => {
      const value = getCssVariableValue(variable)
      cssVariableMap[value.toLowerCase()] = variable // Normalize value to lowercase
    })

    // Function to find the name of a CSS variable from its value
    const findCssVariableName = (value: string): string | null => {
      return cssVariableMap[`#${value}`] || null
    }

    if (searchValue) {
      const name = findCssVariableName(searchValue.toLowerCase()) // Normalize search value to lowercase
      setVariableName(name || 'N/A')
    } else {
      setVariableName('N/A')
    }
  }, [searchValue])

  return (
    <div className='flex max-w-[300px] flex-col gap-4'>
      <SearchBar
        value={searchValue}
        onChange={(value) => setSearchValue(normalizeHexValue(value))}
        placeholder='Color hex value (e.g. 009af0)'
        autoFocus
      />
      <ColorTile variableName={variableName} title='Variable Name' />
    </div>
  )
}

export default ColorLookup

export const ColorTile = ({
  title,
  variableName,
}: {
  title: string
  variableName: string
}) => {
  return (
    <Tile
      id='color-lookup'
      header={{
        title,
        subtitle: variableName,
      }}
      body={
        <div className='flex flex-col items-center gap-2'>
          {variableName !== 'N/A' ? (
            <div
              style={{
                backgroundColor: `var(${variableName})`,
              }}
              className='h-[100px] w-[100px] rounded border border-medium-purple'
            />
          ) : (
            <EmptyState
              primaryText='No Color Found'
              secondaryText='Please enter a valid hex value'
            />
          )}
        </div>
      }
    />
  )
}
