import { memo } from 'react';
import { Group, Line, Text, Circle } from 'react-konva';
import type { Point } from '@house-plan-maker/shared';
import type { MeasurementState } from '../types';

interface MeasureOverlayLayerProps {
  readonly measurement: MeasurementState | null;
  readonly zoom: number;
  readonly panOffset: Point;
}

function toScreen(point: Point, zoom: number, panOffset: Point): { x: number; y: number } {
  return {
    x: point.x * zoom + panOffset.x,
    y: point.y * zoom + panOffset.y,
  };
}

const MEASURE_COLOR = '#e74c3c';
const ENDPOINT_RADIUS = 4;

export const MeasureOverlayLayer = memo(function MeasureOverlayLayer({
  measurement,
  zoom,
  panOffset,
}: MeasureOverlayLayerProps) {
  if (!measurement) return <Group listening={false} />;

  const start = toScreen(measurement.startPoint, zoom, panOffset);
  const end = toScreen(measurement.endPoint, zoom, panOffset);
  const midX = (start.x + end.x) / 2;
  const midY = (start.y + end.y) / 2;

  const distanceM = measurement.distance;
  const label =
    distanceM >= 1
      ? `${distanceM.toFixed(2)} m`
      : `${(distanceM * 100).toFixed(1)} cm`;

  return (
    <Group listening={false}>
      <Line
        points={[start.x, start.y, end.x, end.y]}
        stroke={MEASURE_COLOR}
        strokeWidth={2}
        dash={[8, 4]}
      />
      <Circle
        x={start.x}
        y={start.y}
        radius={ENDPOINT_RADIUS}
        fill={MEASURE_COLOR}
      />
      <Circle
        x={end.x}
        y={end.y}
        radius={ENDPOINT_RADIUS}
        fill={MEASURE_COLOR}
      />
      {distanceM > 0.001 && (
        <Text
          x={midX + 8}
          y={midY - 10}
          text={label}
          fontSize={13}
          fontFamily="sans-serif"
          fontStyle="bold"
          fill={MEASURE_COLOR}
          padding={2}
        />
      )}
    </Group>
  );
});
