import { useMemo } from 'react';
import { Html } from '@react-three/drei';
import type { Point, Wall } from '@house-plan-maker/shared';
import { boundingBox } from '../utils/geometry';
import { wallVector } from './utils/wallGeometry';

interface RoomLabelsProps {
  readonly roomName: string;
  readonly shape: readonly Point[];
  readonly walls: readonly Wall[];
  readonly wallHeight: number;
}

function formatLength(meters: number): string {
  if (meters >= 1) {
    return `${meters.toFixed(2)} m`;
  }
  return `${(meters * 100).toFixed(0)} cm`;
}

export function RoomLabels({ roomName, shape, walls, wallHeight }: RoomLabelsProps) {
  const bb = useMemo(() => boundingBox(shape), [shape]);
  const centerX = (bb.minX + bb.maxX) / 2;
  const centerZ = (bb.minY + bb.maxY) / 2;

  return (
    <group>
      {/* Room name label floating above center */}
      <Html
        position={[centerX, wallHeight + 0.3, centerZ]}
        center
        style={{ pointerEvents: 'none' }}
      >
        <div style={{
          background: 'rgba(0, 0, 0, 0.7)',
          color: '#fff',
          padding: '4px 10px',
          borderRadius: 4,
          fontSize: '13px',
          fontWeight: 600,
          whiteSpace: 'nowrap',
          fontFamily: 'system-ui, sans-serif',
        }}>
          {roomName}
        </div>
      </Html>

      {/* Wall dimension labels */}
      {walls.map((wall) => {
        const { length } = wallVector(wall);
        if (length < 0.1) return null;

        const midX = (wall.startX + wall.endX) / 2;
        const midZ = (wall.startY + wall.endY) / 2;

        return (
          <Html
            key={`dim-${wall.id}`}
            position={[midX, wallHeight + 0.15, midZ]}
            center
            style={{ pointerEvents: 'none' }}
          >
            <div style={{
              background: 'rgba(255, 255, 255, 0.85)',
              color: '#333',
              padding: '2px 6px',
              borderRadius: 3,
              fontSize: '11px',
              whiteSpace: 'nowrap',
              fontFamily: 'system-ui, sans-serif',
              border: '1px solid #ccc',
            }}>
              {formatLength(length)}
            </div>
          </Html>
        );
      })}
    </group>
  );
}
