import { Rect, Transformer } from "react-konva";
import { useRef, useEffect } from "react";
import useEditorStore from "../useEditorStore";

export default function RectangleElement({ element }) {
    const updateElement = useEditorStore((state) => state.updateElement);
    const setSelectedId = useEditorStore((state) => state.setSelectedId);
    const selectedId = useEditorStore((state) => state.selectedId);

    const shapeRef = useRef();
    const trRef = useRef();

    const isSelected = selectedId === element.id;

    useEffect(() => {
        if (isSelected && trRef.current && shapeRef.current) {
            trRef.current.nodes([shapeRef.current]);
            trRef.current.getLayer().batchDraw();
        }
    }, [isSelected]);

    return (
        <>
            <Rect
                ref={shapeRef}
                x={element.x}
                y={element.y}
                width={element.width}
                height={element.height}
                fill={element.fill}
                stroke={element.stroke}
                strokeWidth={element.strokeWidth}
                cornerRadius={element.cornerRadius}
                rotation={element.rotation}
                draggable
                onClick={() => setSelectedId(element.id)}
                onDragEnd={(e) => {
                    const snap = (v) => Math.round(v / 10) * 10;
                    updateElement(element.id, {
                        x: snap(e.target.x()),
                        y: snap(e.target.y()),
                    });
                }}
                onTransformEnd={() => {
                    const node = shapeRef.current;
                    const scaleX = node.scaleX();
                    const scaleY = node.scaleY();

                    node.scaleX(1);
                    node.scaleY(1);

                    updateElement(element.id, {
                        x: node.x(),
                        y: node.y(),
                        width: Math.max(10, node.width() * scaleX),
                        height: Math.max(10, node.height() * scaleY),
                        rotation: node.rotation(),
                    });
                }}
            />

            {isSelected && (
                <Transformer
                    ref={trRef}
                    rotateEnabled={true}
                    boundBoxFunc={(oldBox, newBox) => {
                        if (newBox.width < 10 || newBox.height < 10) {
                            return oldBox;
                        }
                        return newBox;
                    }}
                />
            )}
        </>
    );
}
