import React from 'react'
import { HexColorPicker } from 'react-colorful'
import { ColorPickerBaseProps } from 'react-colorful/dist/types'
import Input from 'antd/lib/input'

export const ColorPicker: React.FC<Partial<ColorPickerBaseProps<string>>> = ({
  color,
  onChange,
  ...props
}) => {
  const onChangeTextColor = (e: React.ChangeEvent<HTMLInputElement>) => {
    let newValue = e.target.value
    if (newValue.length > 7) return
    if (/[^a-fA-F0-9#]/.test(newValue)) return

    if (!newValue.includes('#')) {
      newValue = `#${newValue}`
    }
    onChange && onChange(newValue)
  }
  return (
    <>
      <HexColorPicker {...props} color={color} onChange={onChange} />
      <Input
        className="color-picker-input"
        value={color}
        onChange={onChangeTextColor}
        max={6}
        data-testid="color-picker__input"
      />
    </>
  )
}

export default ColorPicker
