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

export default function LineElement({ 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 (
        <>
            <Line
                ref={shapeRef}
                points={[0, 0, element.width, 0]}
                x={element.x}
                y={element.y}
                stroke={element.color}
                strokeWidth={element.thickness}
                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();

                    node.scaleX(1);

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

            {isSelected && (
                <Transformer
                    ref={trRef}
                    enabledAnchors={["middle-left", "middle-right"]}
                    rotateEnabled={true}
                    boundBoxFunc={(oldBox, newBox) => {
                        if (newBox.width < 20) {
                            return oldBox;
                        }
                        return newBox;
                    }}
                />
            )}
        </>
    );
}
