import React, { useEffect, useState } from "react"
import Input from "../input"
import usePrevious from "../../hooks/use-previous"

const isHex = str => !isNaN(parseInt(str, 16)) || (/^#/.test(str))
const remove = (str, character) => str && str.replace(character, "")
const prepend = (str, character) => isHex(str) ? "".concat(character, str) : str
const trim = (str) => str && str.trim().slice(0, 6)

const ColorPickerInputGroup = ({ onChange, color }) => {
  const [value, setValue] = useState(remove(color, "#"));
  const [focused, setFocused] = useState(false);
  const prevValue = usePrevious(value);

  useEffect(() => {
    const strippedColor = remove(color, "#")
    if (prevValue !== strippedColor && !focused) {
      setValue(strippedColor)
    }
  }, [color, prevValue, focused]);

  const changeColor = (newValue) => {
    const value = trim(remove(newValue, "#"))
    const color = { hex: prepend(value, "#"), source: "hex" }
    setValue(value)
    onChange(color)
  }

  const handleChange = (event) => {
    changeColor(event.target.value)
  }

  const handleFocus = () => {
    setFocused(true)
  }

  const handleBlur = () => {
    setFocused(false)
  }

  const handlePaste = (event) => {
    event.preventDefault()
    changeColor(event.clipboardData.getData("text"))
  }

  return (
    <div className="flex flex-auto items-center">
      <Input
        className="text-base uppercase leading-6 text-gray-900 w-full border-none focus:outline-blue"
        prepend={isHex(value) && '#'}
        style={{ padding: "0" }}
        name="hex"
        value={value}
        onBlur={handleBlur}
        onChange={handleChange}
        onFocus={handleFocus}
        onPaste={handlePaste}
        maxLength="6"
      />
    </div>
  )
}

export default ColorPickerInputGroup
