import { Group, Rect, Text } from 'react-konva';
import type { ProjectedFurniture } from '../utils/projectionMapping';
import { projectionToPixel } from '../utils/projectionMapping';
import { useCanvasColors } from '../utils/canvasThemeColors';

interface ProjectionFurnitureProps {
  readonly projected: ProjectedFurniture;
  readonly wallHeight: number;
  readonly scale: number;
  readonly padding: number;
  readonly isSelected: boolean;
  readonly globalOpacity?: number;
  /** Omit to make the item non-interactive (events fall through). */
  readonly onClick?: () => void;
}

const TYPE_COLORS: Record<string, string> = {
  SHELF: '#d4a574',
  BOOKCASE: '#b8860b',
  WARDROBE: '#8b7355',
  DRESSER: '#a0845c',
  DESK: '#c9a96e',
  TABLE: '#deb887',
};

/** Render a furniture item in wall elevation view. */
export function ProjectionFurniture({
  projected,
  wallHeight,
  scale,
  padding,
  isSelected,
  globalOpacity = 1,
  onClick,
}: ProjectionFurnitureProps) {
  const colors = useCanvasColors();
  const { rect, item } = projected;

  const topLeft = projectionToPixel(rect.x, rect.y + rect.height, wallHeight, scale, padding);
  const pxWidth = rect.width * scale;
  const pxHeight = rect.height * scale;

  const color = TYPE_COLORS[item.type] ?? '#a0845c';

  const itemOpacity = (item.opacity ?? 1) * globalOpacity;
  const interactive = onClick !== undefined;
  return (
    <Group onClick={onClick} opacity={itemOpacity} listening={interactive}>
      <Rect
        x={topLeft.x}
        y={topLeft.y}
        width={pxWidth}
        height={pxHeight}
        fill={isSelected ? colors.selectedFill : color}
        stroke={isSelected ? colors.selectedStroke : colors.furnitureStroke}
        strokeWidth={isSelected ? 2 : 1}
        opacity={0.7}
      />
      {/* Furniture label */}
      <Text
        x={topLeft.x}
        y={topLeft.y + pxHeight / 2 - 5}
        width={pxWidth}
        text={item.label ?? item.type}
        align="center"
        fontSize={9}
        fill={isSelected ? colors.selectedText : colors.furnitureText}
        ellipsis
      />
    </Group>
  );
}
