import React, { memo, useEffect, useMemo, useRef, useState } from "react";
import { ColorAbsorptionOutlined } from "@easyv/react-icons";
import { Panel as ColorPickerPanel } from "rc-color-picker";
import "rc-color-picker/assets/index.css";
import { useDebounceFn } from "ahooks";
import classNames from "classnames";
import Color from "rc-color-picker/lib/helpers/color";
import styles from "./index.less";

export default memo(function ColorPicker({
  record = null,
  color = "rgba(255,0,255,0.5)",
  onChange,
  active,
  unAlpha,
}) {
  const isControlled = useRef(true);
  const thisAlpha = useRef(100);
  const colorObj = new Color(color);
  const [isClicked, setIsClicked] = useState(false);
  const eyeDropperEnable = window.EyeDropper ? true : false;
  const domRef = useRef(null);
  useMemo(() => {
    isControlled.current = true;
  }, [active, record]);
  const { run } = useDebounceFn(
    ({ color, alpha }) => {
      isControlled.current = false;
      let newColor;
      let rgbColor;
      if (alpha === 100) {
        newColor = color;
        thisAlpha.current = 100;
      } else {
        thisAlpha.current = alpha;
        rgbColor = new Color(color).RGB;
        newColor = `RGBA(${rgbColor[0]},${rgbColor[1]},${rgbColor[2]},${alpha / 100})`;
      }
      onChange(newColor);
    },
    { wait: 100, leading: true, trailing: false },
  );
  useEffect(() => {
    const a = document.querySelector(".rc-color-picker-panel-wrap-has-alpha");
    if (!eyeDropperEnable && a) {
      a.style = "width: 100%;margin-left: 0;";
    }
  }, [domRef.current]);
  const handleClick = (e) => {
    if (!window.EyeDropper) {
      return;
    }
    setIsClicked(true);
    const eyeDropper = new EyeDropper();
    eyeDropper
      .open()
      .then((result) => {
        if (result) {
          run({ color: result.sRGBHex, alpha: thisAlpha.current });
        }
        setIsClicked(false);
      })
      .catch((error) => {
        console.log(error);
        setIsClicked(false);
      });
  };

  return (
    <>
      {eyeDropperEnable && (
        <div
          className={classNames(styles.iconBox, { [styles.clicked]: isClicked })}
          onClick={handleClick}
        >
          <ColorAbsorptionOutlined className={styles.icon} />
        </div>
      )}
      {isControlled.current ? (
        <ColorPickerPanel
          ref={domRef}
          className={classNames(styles.colorPicker, {
            [styles.colorPickerBack]: !eyeDropperEnable,
          })}
          color={colorObj.toHexString()}
          enableAlpha={!unAlpha}
          alpha={colorObj.alpha}
          mode="RGB"
          onChange={run}
        />
      ) : (
        <ColorPickerPanel
          ref={domRef}
          className={classNames(styles.colorPicker, {
            [styles.colorPickerBack]: !eyeDropperEnable,
          })}
          mode="RGB"
          onChange={run}
          enableAlpha={!unAlpha}
        />
      )}
    </>
  );
});
