import { Suspense, useEffect, useRef, useState } from "react";
import DragableBox from "./DragableBox";
import { PhAngle } from "./PhAngle";

type Coordinates = {
  x: number;
  y: number;
}

export default function CropSelector() {
  const [firstDragable, setFirstDragable] = useState<Coordinates>({
    x: 0,
    y: 0
  });
  const [secondDragable, setSecondDragable] = useState<Coordinates>({
    x: 100,
    y: 100
  });
  const [selectorPosition, setSelectorPosition] = useState<Coordinates>({
    x: 0,
    y: 0
  });

  const containerRef = useRef<HTMLDivElement>(null);

  // Update selector position and dimensions based on handle positions
  useEffect(() => {
    setSelectorPosition({
      x: Math.min(firstDragable.x, secondDragable.x),
      y: Math.min(firstDragable.y, secondDragable.y)
    });
  }, [firstDragable, secondDragable]);

  // Calculate selector dimensions
  const selectorWidth = Math.abs(secondDragable.x - firstDragable.x);
  const selectorHeight = Math.abs(secondDragable.y - firstDragable.y);

  // Handle selector drag
  const handleSelectorDrag = (newPosition: Coordinates) => {
    const deltaX = newPosition.x - selectorPosition.x;
    const deltaY = newPosition.y - selectorPosition.y;

    setFirstDragable(prev => ({
      x: Math.min(firstDragable.x, secondDragable.x) + deltaX,
      y: Math.min(firstDragable.y, secondDragable.y) + deltaY
    }));

    setSecondDragable(prev => ({
      x: Math.max(firstDragable.x, secondDragable.x) + deltaX,
      y: Math.max(firstDragable.y, secondDragable.y) + deltaY
    }));
  };

  return (
    <div className="flex flex-col h-screen w-screen justify-center items-center">
      <Suspense fallback={<p>Loading...</p>}>
        <div ref={containerRef} className="relative w-1/3 h-1/3 border-black border">
          <DragableBox
            position={selectorPosition}
            mode="box"
            width={selectorWidth}
            height={selectorHeight}
            coordSetter={setSelectorPosition}
            onDrag={handleSelectorDrag}
            className="border border-black"
          />
          <DragableBox position={firstDragable} coordSetter={setFirstDragable} mode="handle">
            <PhAngle />
          </DragableBox>
          <DragableBox position={secondDragable} coordSetter={setSecondDragable} mode="handle">
            <PhAngle />
          </DragableBox>
        </div>
      </Suspense>
    </div>
  );
}
