import React, { useCallback, useEffect, useState } from "react"
import { SketchPicker } from 'react-color'
import style from './index.less'
type props = {
    onColor: (color: string) => void,
    defaultColor?: string,
    value?: string,
}

const ColorPicker = (props: props) => {
    let { onColor, defaultColor = "#000000", value } = props
    const [displayColorPicker, setDisplayColorPicker] = useState<boolean>(false)
    const [color, setColor] = useState<any>(defaultColor)

    const handleClick = useCallback(() => {
        setDisplayColorPicker(!displayColorPicker)
    }, [])

    const handleClose = useCallback(() => {
        setDisplayColorPicker(false)
    }, [])

    const handleChange = useCallback((e: any) => {
        setColor(e.hex)
        onColor(e.hex)
    }, [color])

    useEffect(() => {
        onColor(color)
    }, [])

    useEffect(() => {
        if (value) {
            setColor(value)
            onColor(value)
        }
    }, [value])
    
    return <>
        <div className={style.colorPicker}>
            <div className={style.swatch} onClick={handleClick}>
                <div className={style.color} style={{ backgroundColor: color }} />
            </div>
            {
                displayColorPicker ? <div className={style.popover}>
                    <div className={style.cover} onClick={handleClose} />
                    <SketchPicker color={color} onChange={handleChange} className={style.sketchPicker} />
                </div> : null
            }

        </div>
    </>
}

export default React.memo(ColorPicker)