import { useEffect, useRef } from "react";
import { Line } from "react-konva";
import Konva from "konva";
import type { ShapeProps } from "./types";

const LineShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, draggable }: ShapeProps) => {
    const shapeRef = useRef<Konva.Line>(null);

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

    return (
        <Line
            ref={shapeRef}
            x={obj.x}
            y={obj.y}
            points={[0, 0, (obj.width || 0) - obj.x, (obj.height || 0) - obj.y]}
            stroke={isSelected ? "#3b82f6" : obj.stroke || "#000000"}
            strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
            rotation={obj.rotation || 0}
            draggable={draggable}
            onClick={() => {
                if (shapeRef.current) {
                    onSelect(obj.id, shapeRef.current);
                }
            }}
            onDragEnd={(e) => {
                const node = e.target;
                onUpdate(obj.id, {
                    x: node.x(),
                    y: node.y(),
                });
            }}
        />
    );
};

export default LineShape;

