import React, { memo } from "react";

export default memo((props) => {
  const { direction, values, i, dispatch, containerRef, imgDimensions } = props;
  const isHorizontal = direction === "horizontal";
  const index = isHorizontal ? (i === 0 ? 0 : 2) : i === 0 ? 3 : 1;
  const style = isHorizontal
    ? {
        position: "absolute",
        width: "100%",
        height: "3px",
        cursor: "ns-resize",
        top: "calc(" + values[i] + "% - 2px)",
        background: "#3A89FE",
      }
    : {
        position: "absolute",
        width: "3px",
        height: "100%",
        cursor: "ew-resize",
        left: "calc(" + values[i] + "% - 2px)",
        background: "#3A89FE",
      };

  const down = () => {
    const move = (e) => {
      const containerRect = containerRef.current.getBoundingClientRect();
      const containerWidth = containerRect.width;
      const containerHeight = containerRect.height;

      const { width: imgWidth, height: imgHeight } = imgDimensions;

      const widthRatio = imgWidth / containerWidth;
      const heightRatio = imgHeight / containerHeight;

      const adjustedMovement = isHorizontal ? e.movementY * heightRatio : e.movementX * widthRatio;

      dispatch({
        type: index,
        value: adjustedMovement,
      });
    };

    const up = () => {
      dispatch({
        type: "update",
        value: index,
        direction,
      });
      document.removeEventListener("mousemove", move);
      document.removeEventListener("mouseup", up);
    };

    document.addEventListener("mousemove", move);
    document.addEventListener("mouseup", up);
  };

  return <div style={style} onMouseDown={down}></div>;
});
