import React, { useCallback, useEffect, useRef, useState } from "react";
import { Col, Row } from "antd";
import { EasyNumber } from "config-types";
import debounce from "lodash/debounce";
import Draggable from "react-draggable";
import styles from "./index.less";

const width = 56;
const height = 38;

export default function EasyPosition({
  value = [],
  onChange,
  showContainer = true,
  min = 0,
  max = 100,
}) {
  const [pos, setPos] = useState(value);

  const dragHandlerRef = useRef();

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

  useEffect(() => {
    dragHandlerRef.current = debounce((newPos) => {
      onChange(newPos);
    }, 300);
  }, [onChange]);

  const handleXChange = (x) => {
    setPos((prev) => {
      let newPos = [x / 100, prev[1]];
      dragHandlerRef.current(newPos);
      return newPos;
    });
  };

  const handleYChange = (y) => {
    setPos((prev) => {
      let newPos = [prev[0], y / 100];
      dragHandlerRef.current(newPos);
      return newPos;
    });
  };

  const handleDrag = useCallback((e, data) => {
    const { x, y } = data;
    let newPos = [x / width, y / height];
    setPos(newPos);
    dragHandlerRef.current(newPos);
  }, []);

  const x = width * pos[0];
  const y = height * pos[1];

  return (
    <div
      className={styles.row}
      style={{
        gap: showContainer ? "0" : "8px",
      }}
    >
      {showContainer && (
        <div className={styles.col}>
          <div className={styles.container}>
            <div className={styles.grid}>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
              <span className={styles.item}></span>
            </div>
            <Draggable bounds="parent" position={{ x: x, y: y }} onDrag={handleDrag}>
              <span className={styles.item + " " + styles.drag}></span>
            </Draggable>
          </div>
        </div>
      )}

      <div
        className={styles.col}
        style={{
          flex: showContainer ? "none" : "1",
        }}
      >
        <EasyNumber
          value={Math.floor(pos[0] * 100)}
          min={min}
          max={max}
          suffix="%"
          onChange={handleXChange}
        />
        <label className={styles.label}>X</label>
      </div>
      <div
        className={styles.col}
        style={{
          flex: showContainer ? "none" : "1",
        }}
      >
        <EasyNumber
          value={Math.floor(pos[1] * 100)}
          min={min}
          max={max}
          suffix="%"
          onChange={handleYChange}
        />
        <label className={styles.label}>Y</label>
      </div>
    </div>
  );
}
