import type { Point, FurnitureItem } from '@house-plan-maker/shared';
import { DEFAULT_POSITION_ANCHOR } from '@house-plan-maker/shared';
import { generateLocalId } from '../utils/geometry';
import type { FurnitureDef } from '../symbols/furniture';

export interface FurniturePlacementPreview {
  readonly x: number;
  readonly y: number;
  readonly width: number;
  readonly depth: number;
  readonly rotation: number;
  readonly isValid: boolean;
}

/**
 * Compute furniture placement preview.
 * New furniture uses the default anchor (middle/middle), so the cursor world
 * point IS the (x, y) — no offset needed.
 */
export function computeFurniturePreview(
  worldPoint: Point,
  furnitureDef: FurnitureDef,
  rotation: number = 0,
): FurniturePlacementPreview {
  return {
    x: worldPoint.x,
    y: worldPoint.y,
    width: furnitureDef.width,
    depth: furnitureDef.depth,
    rotation,
    isValid: true,
  };
}

/**
 * Create a FurnitureItem from placement data.
 * Propagates the FurnitureDef's defaultMetadata into item.metadata so
 * presets like plant variants or flower colours apply on first render.
 */
export function createFurnitureItemFromPlacement(
  roomId: string,
  preview: FurniturePlacementPreview,
  furnitureDef: FurnitureDef,
): FurnitureItem {
  // Shallow-copy the default metadata so later mutations on the item don't
  // leak back into the static FurnitureDef table.
  const metadata: Record<string, unknown> | null = furnitureDef.defaultMetadata
    ? { ...furnitureDef.defaultMetadata }
    : null;

  return {
    id: generateLocalId(),
    roomId,
    type: furnitureDef.type,
    x: preview.x,
    y: preview.y,
    width: preview.width,
    depth: preview.depth,
    height: furnitureDef.height,
    rotation: preview.rotation,
    elevationFromFloor:
      furnitureDef.type === 'AC_UNIT'
        ? 2.2
        : furnitureDef.type === 'WALL_COLLAGE'
          ? 1.4 // eye level — user can adjust in the panel
          : furnitureDef.type === 'RADIATOR'
            ? 0.12 // small clearance from the floor (typical)
            : furnitureDef.type === 'MIRROR' &&
                (furnitureDef.defaultMetadata?.['variant'] as string | undefined) === 'wall'
              ? Math.max(0, 1.5 - furnitureDef.height / 2) // hang so centre sits around eye level
              : furnitureDef.height <= 0.05
                ? 1.2
                : 0,
    label: furnitureDef.label,
    positionAnchor: DEFAULT_POSITION_ANCHOR,
    metadata,
  };
}

/** Rotate a furniture item by the given delta in degrees. */
export function rotateFurniture(item: FurnitureItem, deltaDeg: number): FurnitureItem {
  return {
    ...item,
    rotation: (item.rotation + deltaDeg) % 360,
  };
}

/** Move a furniture item to a new position. */
export function moveFurniture(item: FurnitureItem, newPos: Point): FurnitureItem {
  return {
    ...item,
    x: newPos.x,
    y: newPos.y,
  };
}
