import {useRef, useEffect, useCallback} from "react";
import {Transformer} from "react-konva";
import type Konva from "konva";
import type {Stage as StageType} from "konva/lib/Stage";
import {useCanvasStore} from "@/stores/canvasStore";

interface TransformableShapeProps {
  selectedIds: string[];
  stageRef: React.RefObject<StageType | null>;
}

export function TransformableShape({
  selectedIds,
  stageRef,
}: TransformableShapeProps) {
  const transformerRef = useRef<Konva.Transformer>(null);

  // Use individual selectors to avoid unnecessary re-renders
  const updateElement = useCanvasStore((state) => state.updateElement);
  const resizeElement = useCanvasStore((state) => state.resizeElement);
  const rotateElement = useCanvasStore((state) => state.rotateElement);

  // Attach transformer to selected nodes
  useEffect(() => {
    const transformer = transformerRef.current;
    const stage = stageRef.current;

    if (!transformer || !stage) return;

    // Find nodes by ID
    const nodes = selectedIds
      .map((id) => stage.findOne(`#${id}`))
      .filter((node): node is Konva.Node => node !== undefined);

    transformer.nodes(nodes);
    transformer.getLayer()?.batchDraw();
  }, [selectedIds, stageRef]);

  // Handle transform end
  const handleTransformEnd = useCallback(() => {
    const transformer = transformerRef.current;
    if (!transformer) return;

    const nodes = transformer.nodes();

    nodes.forEach((node) => {
      const id = node.id();
      if (!id) return;

      // Get the new scale (uniform since keepRatio=true)
      const scale = node.scaleX(); // scaleX === scaleY when keepRatio is true

      // Reset scale and update size
      node.scaleX(1);
      node.scaleY(1);

      const newWidth = Math.max(10, node.width() * scale);
      const newHeight = Math.max(10, node.height() * scale);

      resizeElement(id, {
        width: newWidth,
        height: newHeight,
      });

      rotateElement(id, node.rotation());

      updateElement(id, {
        position: {
          x: node.x(),
          y: node.y(),
        },
      });
    });
  }, [updateElement, resizeElement, rotateElement]);

  if (selectedIds.length === 0) {
    return null;
  }

  return (
    <Transformer
      ref={transformerRef}
      boundBoxFunc={(oldBox, newBox) => {
        // Limit minimum size
        if (Math.abs(newBox.width) < 10 || Math.abs(newBox.height) < 10) {
          return oldBox;
        }
        return newBox;
      }}
      onTransformEnd={handleTransformEnd}
      rotateEnabled={true}
      keepRatio={true}
      enabledAnchors={["top-left", "top-right", "bottom-left", "bottom-right"]}
      anchorSize={8}
      anchorCornerRadius={2}
      anchorFill="#ffffff"
      anchorStroke="#3b82f6"
      anchorStrokeWidth={1}
      borderStroke="#3b82f6"
      borderStrokeWidth={1}
      borderDash={[4, 4]}
      rotateAnchorOffset={20}
      padding={2}
      flipEnabled={false}
      ignoreStroke={true}
    />
  );
}
