import { insetRect, Rect } from "@noya-app/noya-geometry";
import { Group, Rectangle } from "@noya-app/noya-graphics";
import React, { useMemo } from "react";
import { BaseCanvasData, getCanvasTransform } from "../plugins/baseCanvas";
import { useReactCanvas } from "../plugins/ReactCanvas";
import { ScaleData } from "../plugins/scalePlugin";
import { getDragHandles } from "../utils/dragHandleUtils";

export function DragHandles({
  selectionRect,
  data,
}: {
  selectionRect?: Rect;
  data?: Pick<BaseCanvasData, "zoom" | "origin"> &
    Pick<ScaleData, "dragHandleSize" | "hoveredDragHandleDirection">;
}) {
  const ReactCanvas = useReactCanvas();
  const canvasData = ReactCanvas.useData() as ScaleData & BaseCanvasData;

  data = data ?? canvasData;

  const transform = useMemo(() => getCanvasTransform(data), [data]);

  const dragHandles = useMemo(() => {
    return selectionRect
      ? getDragHandles({
          selectionRect,
          data: { zoom: data.zoom, dragHandleSize: data.dragHandleSize },
        })
      : [];
  }, [selectionRect, data.zoom, data.dragHandleSize]);

  return (
    <Group transform={transform}>
      {dragHandles.map((handle) => {
        const inset = 0.5 / data.zoom;
        const rect = insetRect(handle.rect, inset);

        return (
          <React.Fragment key={handle.compassDirection}>
            <Rectangle
              rect={rect}
              paint={{
                style: "fill",
                color: "#FFFFFF",
              }}
            />
            <Rectangle
              rect={rect}
              paint={{
                style: "stroke",
                strokeWidth: handle.strokeWidth,
                color:
                  data.hoveredDragHandleDirection === handle.compassDirection
                    ? "#FFA500"
                    : "#1E90FF",
              }}
            />
          </React.Fragment>
        );
      })}
    </Group>
  );
}
