import { Layer, Line, Circle } from "react-konva";
import type { CustomShapeDrawingState } from "./useCustomShapeDrawing";

const CLOSE_THRESHOLD = 12;
const ANCHOR_RADIUS = 5;
const FIRST_ANCHOR_COLOR = "#ef4444"; // red — marks the closing vertex
const ANCHOR_COLOR = "#3b82f6";
const PREVIEW_LINE_COLOR = "#3b82f6";
const CLOSE_HINT_FILL = "rgba(239, 68, 68, 0.15)";

type CustomShapeDrawingLayerProps = {
  drawingState: CustomShapeDrawingState;
};

/**
 * Konva Layer rendered on top of all objects while the user is drawing a custom polygon.
 * Shows:
 *   • A dashed preview line through all placed vertices + the current cursor position
 *   • Circular anchor handles at each vertex (red for the first, blue for the rest)
 *   • A translucent red ring around the first vertex when the cursor is close enough to close the shape
 *
 * This layer has `listening={false}` so it never intercepts mouse events.
 */
const CustomShapeDrawingLayer = ({ drawingState }: CustomShapeDrawingLayerProps) => {
  const { isActive, points, previewPoint } = drawingState;

  if (!isActive || points.length === 0) return null;

  // Build the flat points array for the preview line
  const allDisplayPoints = previewPoint ? [...points, previewPoint] : points;
  const linePoints = allDisplayPoints.flatMap((p) => [p.x, p.y]);

  const showCloseHint =
    previewPoint !== null &&
    points.length >= 3 &&
    Math.hypot(previewPoint.x - points[0].x, previewPoint.y - points[0].y) <=
      CLOSE_THRESHOLD;

  return (
    <Layer listening={false}>
      {/* Dashed preview line */}
      <Line
        points={linePoints}
        stroke={PREVIEW_LINE_COLOR}
        strokeWidth={2}
        dash={[6, 3]}
        perfectDrawEnabled={false}
        lineCap="round"
        lineJoin="round"
      />

      {/* Vertex anchor dots */}
      {points.map((p, i) => (
        <Circle
          key={i}
          x={p.x}
          y={p.y}
          radius={ANCHOR_RADIUS}
          fill={i === 0 ? FIRST_ANCHOR_COLOR : ANCHOR_COLOR}
          stroke="white"
          strokeWidth={1.5}
          perfectDrawEnabled={false}
        />
      ))}

      {/* Close-shape hint: translucent ring on first vertex */}
      {showCloseHint && (
        <Circle
          x={points[0].x}
          y={points[0].y}
          radius={CLOSE_THRESHOLD}
          stroke={FIRST_ANCHOR_COLOR}
          strokeWidth={1.5}
          fill={CLOSE_HINT_FILL}
          dash={[4, 2]}
          perfectDrawEnabled={false}
        />
      )}
    </Layer>
  );
};

export default CustomShapeDrawingLayer;
