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,
    type?: 'rgba'
}

const ColorPicker = (props: props) => {
    let { onColor, defaultColor = "conic-gradient(red, yellow, lime, aqua, blue, magenta, red)", value, type } = 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) => {
        let hex = e.hex
        let {r,g,b,a} = e.rgb
        let rgba = `rgba(${r},${g},${b},${a})`
        setColor(type === 'rgba' ? rgba : hex)
        onColor(type === 'rgba' ? rgba : hex)
    }, [color, type])

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

    useEffect(() => {
        if (value) {
            setColor(value)
            onColor(value)
        }
    }, [value])
    useEffect(()=>{
        console.log('defaultColor',defaultColor)
        setColor(defaultColor)
    },[defaultColor])
    return <>
        <div className={style.colorPicker}>
            <div className={style.swatch} onClick={handleClick}>
                <div className={style.color} style={{ background: 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)