import React, { useState, useEffect } from 'react';
import { SketchPicker } from 'react-color';
import ColorPond from './ColorPond';
import './index.scss';

/**
 * 公共颜色拾取区域
 * @param value 色值
 * @param handleChange 变更回调
 * @return {*}
 * @constructor
 */
const CommonColorPicker = ({
  value,
  dark,
  handleChange
}: ICommonColorPicker) => {
  const [color, setColor] = useState<string>(value);

  // 颜色变更
  const changeColor = ({ hex, rgb = { a: 1, r: 0, g: 0, b: 0 } }: IColor) => {
    let val = hex;
    if (rgb.a < 1) {
      val = `rgba(${rgb.r},${rgb.g},${rgb.b},${rgb.a})`;
    }
    typeof handleChange === 'function' && handleChange(val);
    setColor(val);
  };

  useEffect(() => {
    setColor(value);
  }, [value]);

  return (
    <div className="common">
      <ColorPond color={color} dark={dark} onChange={changeColor} />
      <SketchPicker
        className={`sketchCommon ${dark ? 'sketch' : ''}`}
        presetColors={[]}
        color={color}
        onChange={changeColor}
      />
    </div>
  );
};

export default CommonColorPicker;

export interface ICommonColorPicker {
  value?: string;
  dark?: boolean;
  handleChange?: Function;
}

export interface IColor {
  hex: string;
  rgb: IRgb;
}

export interface IRgb {
  a: number;
  r: number;
  g: number;
  b: number;
}
