import React, { useCallback, useEffect, useRef, useState } from "react";
import { FormGroup } from "layout";
import ModalColor from "../../easy-design/modal-color";
import styles from "./index.less";

const { Col } = FormGroup;

export default function EasyColorControl({ onChange, value }) {
  const [show, setShow] = useState(false);
  const modalRef = useRef(null);
  const previewRef = useRef(null);
  const [position, setPosition] = useState({ x: 0, y: 0 });

  const handleClick = () => {
    setShow(true);
  };

  const handleHide = useCallback(() => {
    setShow(false);
  }, [show]);

  useEffect(() => {
    if (show) {
      let targetRect = previewRef.current.getBoundingClientRect();
      let pickerRect = modalRef.current.getBoundingClientRect();
      let windowHeight = document.documentElement.clientHeight;
      let windowWidth = document.documentElement.clientWidth;
      let top =
        windowHeight - targetRect.bottom < pickerRect.height
          ? targetRect.top - pickerRect.height - 4 < 0
            ? 0
            : targetRect.top - pickerRect.height - 4
          : targetRect.bottom + 4;
      let left =
        windowWidth - targetRect.left + 95 < pickerRect.width
          ? windowWidth - pickerRect.width
          : targetRect.left - 95;
      setPosition({ x: left, y: top });
    }
  }, [show]);

  return (
    <FormGroup style={{ marginBottom: -4 }}>
      <Col span={12}>
        <span className={styles.square} onClick={handleClick} ref={previewRef}>
          <span className={styles.control}></span>
        </span>
        {show && (
          <ModalColor
            ref={modalRef}
            cancel={handleHide}
            onChange={onChange}
            position={position}
            value={value}
          />
        )}
      </Col>
    </FormGroup>
  );
}
