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

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

  const points = obj.points ?? [];
  if (points.length < 4) return null;

  const actualStrokeWidth = obj.strokeWidth ?? 3;
  const hasStroke = actualStrokeWidth > 0;

  const displayStroke = isSelected
    ? (hasStroke ? obj.stroke : "#3b82f6")
    : (hasStroke ? obj.stroke : "#000000");

  const displayStrokeWidth = isSelected
    ? (hasStroke ? actualStrokeWidth : 3)
    : actualStrokeWidth;

  return (
    <Line
      ref={shapeRef}
      id={obj.id}
      name="canvas-object"
      x={obj.x}
      y={obj.y}
      points={points}
      closed={false}
      stroke={displayStroke}
      strokeWidth={displayStrokeWidth}
      tension={obj.tension ?? 0.5}
      lineCap="round"
      lineJoin="round"
      hitStrokeWidth={Math.max(20, displayStrokeWidth + 10)}
      perfectDrawEnabled={false}
      rotation={obj.rotation ?? 0}
      opacity={(obj.opacity ?? 100) / 100}
      draggable={draggable}
      onClick={(e) => {
        if (shapeRef.current) {
          onSelect(obj.id, shapeRef.current, e);
        }
      }}
      onDragMove={(e) => {
        e.target.getLayer()?.batchDraw();
      }}
      onDragEnd={(e) => {
        const node = e.target;
        onUpdate(obj.id, {
          x: node.x(),
          y: node.y(),
        });
      }}
    />
  );
};

export default PencilShape;
