import React, { useEffect, useRef, useState } from 'react';
import { Input } from 'antd';
import { SketchPicker } from 'react-color';
import FormItem from '../FormItem/FormItem'
import s from './index.module.less';
import defaultProps from "./default"

const ColorPicker: React.FC = (item:any) => {
  const props = item || defaultProps
  const {componentType,FormItemProps} = props
  const colorRef: any = useRef();
  const [backgroundColor, SetBackgroundColor] = useState(
    'conic-gradient(red,yellow,lime,aqua,blue,fuchsia,red)',
  );
  const [bgColor, SetbgColor] = useState<string>("");
  const [visibility, SetVisibility] = useState(false);

  const clickHandler = (e: any) => {
    if (!colorRef.current) {
      return;
    }
    if (!colorRef.current.contains(e.target) && colorRef.current !== e.target) {
      SetVisibility(false);
    }
  };

  useEffect(() => {
    window.addEventListener('click', clickHandler);
    return () => {
      window.removeEventListener('click', clickHandler);
    };
  }, []);

  const handleChange = (color: any) => {
    SetBackgroundColor(color.rgb);
    SetbgColor(`rgba(${color.rgb.r},${color.rgb.g},${color.rgb.b},${color.rgb.a})`);
  };

  return (
    <>
      {
        componentType === 'FormItem' ? <FormItem FormItemProps={...FormItemProps}>
          <div ref={colorRef} className={s.colorPicker}>
            <Input
              value={bgColor}
              placeholder="点击选色器选择颜色"
              onClick={() => {
                SetVisibility(true);
              }}
              suffix={<div 
                onClick={() => {
                  SetVisibility(true);
                }}
                style={{
                  borderRadius:"50%", width: '20px', height: '20px', 
                  background: bgColor || backgroundColor
                }}></div>}
              readOnly
            />
            {visibility ? (
              <SketchPicker 
                color={backgroundColor} 
                onChange={(color: any) => handleChange(color)} />
              ) : null}
          </div>
        </FormItem> :<div ref={colorRef} className={s.colorPicker}>
          <Input
            value={bgColor}
            placeholder="点击选色器选择颜色"
            onClick={() => {

              SetVisibility(true);
            }}
            suffix={<div 
              onClick={() => {
                SetVisibility(true);
              }}
              style={{
                borderRadius:"50%", width: '20px', height: '20px', 
                background: bgColor || backgroundColor
              }}></div>}
            readOnly
          />
          {visibility ? (
            <SketchPicker 
              color={backgroundColor} 
              onChange={(color: any) => handleChange(color)} />
            ) : null}
        </div>
      }
    </>
  );
};

export default ColorPicker;
