import { useMemo } from 'react';
import { Group, Rect, Text } from 'react-konva';
import type { Point } from '@house-plan-maker/shared';
import { polygonArea, boundingBox } from '../utils/geometry';

interface RoomLabelLayerProps {
  readonly roomName: string;
  readonly roomShape: readonly Point[];
  readonly zoom: number;
  readonly panOffset: Point;
}

const LABEL_FONT_SIZE = 13;
const AREA_FONT_SIZE = 11;
const LABEL_COLOR = '#343a40';
const AREA_COLOR = '#868e96';
const BG_COLOR = 'rgba(255, 255, 255, 0.75)';
const BG_PADDING_X = 8;
const BG_PADDING_Y = 4;
const LINE_SPACING = 4;
const MIN_ZOOM_FOR_LABELS = 30;

export function RoomLabelLayer({
  roomName,
  roomShape,
  zoom,
  panOffset,
}: RoomLabelLayerProps) {
  const area = useMemo(
    () => (roomShape.length >= 3 ? polygonArea(roomShape) : 0),
    [roomShape],
  );

  const bbox = useMemo(
    () => (roomShape.length >= 2 ? boundingBox(roomShape) : null),
    [roomShape],
  );

  if (!bbox || zoom < MIN_ZOOM_FOR_LABELS) {
    return <Group listening={false} />;
  }

  const areaText = `${(Math.round(area * 100) / 100).toFixed(1)} m\u00B2`;

  // Generous text-width estimate: bold font + multibyte glyphs (Cyrillic, etc.)
  // can exceed Latin averages, so we over-allocate to avoid line wrapping.
  const nameWidth = roomName.length * (LABEL_FONT_SIZE * 0.75) + 6;
  const areaWidth = areaText.length * (AREA_FONT_SIZE * 0.7) + 6;
  const maxWidth = Math.max(nameWidth, areaWidth);
  const totalHeight = LABEL_FONT_SIZE + LINE_SPACING + AREA_FONT_SIZE;

  const bgWidth = maxWidth + BG_PADDING_X * 2;
  const bgHeight = totalHeight + BG_PADDING_Y * 2;

  // Anchor the badge just outside the room's top-left corner so it stays out of
  // the way of any walls, openings, or items inside the room.
  const cornerScreenX = bbox.minX * zoom + panOffset.x;
  const cornerScreenY = bbox.minY * zoom + panOffset.y;
  const screenX = cornerScreenX;
  const screenY = cornerScreenY - bgHeight - 6;

  return (
    <Group listening={false}>
      <Group x={screenX} y={screenY}>
        {/* Semi-transparent background */}
        <Rect
          x={0}
          y={0}
          width={bgWidth}
          height={bgHeight}
          fill={BG_COLOR}
          cornerRadius={4}
          listening={false}
        />
        {/* Room name */}
        <Text
          x={BG_PADDING_X}
          y={BG_PADDING_Y}
          text={roomName}
          fontSize={LABEL_FONT_SIZE}
          fontStyle="bold"
          fill={LABEL_COLOR}
          align="left"
          wrap="none"
          listening={false}
        />
        {/* Area */}
        <Text
          x={BG_PADDING_X}
          y={BG_PADDING_Y + LABEL_FONT_SIZE + LINE_SPACING}
          text={areaText}
          fontSize={AREA_FONT_SIZE}
          fill={AREA_COLOR}
          align="left"
          wrap="none"
          listening={false}
        />
      </Group>
    </Group>
  );
}
