import { useMemo } from 'react';
import { Text } from '@react-three/drei';
import * as THREE from 'three';
import type { Room3D } from '../../lib/layoutApi';
import { PlantPosition, VisMode, COLORS } from './types';
import { SmartRack, HierarchyContext } from './SmartRack';
import { RoomSummaryOverlay } from './SummaryOverlay';

// Convert pixel coordinates to world units
const SCALE = 0.1;

// Mock environment data
const getMockRoomEnv = (roomName: string) => {
    const hash = roomName.split('').reduce((a, b) => a + b.charCodeAt(0), 0);
    return {
        temp: 68 + (hash % 15),
        humidity: 40 + (hash % 40),
    };
};

const lerpColor = (c1: string, c2: string, t: number) => {
    const c1c = new THREE.Color(c1);
    const c2c = new THREE.Color(c2);
    return '#' + c1c.lerp(c2c, Math.min(1, Math.max(0, t))).getHexString();
};

interface RoomObjectProps {
    room: Room3D;
    visMode: VisMode;
    onPlantClick: (plant: PlantPosition) => void;
    highlightedTags?: string[];
    dimMode?: boolean;
    hierarchy?: Omit<HierarchyContext, 'room'>;
    timelineDate?: Date;
}

export function RoomObject({ room, visMode, onPlantClick, highlightedTags, dimMode, hierarchy, timelineDate }: RoomObjectProps) {
    const env = getMockRoomEnv(room.name);

    // Scale room dimensions to world units
    const scaledRoom = {
        posX: room.posX * SCALE,
        posY: room.posY * SCALE,
        width: room.width * SCALE,
        height: room.height * SCALE,
    };

    let floorColor: string = COLORS.ROOM_FLOOR;
    if (visMode === 'TEMP') {
        const t = (env.temp - 65) / 20;
        floorColor = t < 0.5
            ? lerpColor(COLORS.TEMP_LOW, COLORS.TEMP_OPTIMAL, t * 2)
            : lerpColor(COLORS.TEMP_OPTIMAL, COLORS.TEMP_HIGH, (t - 0.5) * 2);
    } else if (visMode === 'HUMIDITY') {
        const t = (env.humidity - 40) / 40;
        floorColor = t < 0.5
            ? lerpColor(COLORS.HUMIDITY_DRY, COLORS.HUMIDITY_OPTIMAL, t * 2)
            : lerpColor(COLORS.HUMIDITY_OPTIMAL, COLORS.HUMIDITY_WET, (t - 0.5) * 2);
    }

    // Calculate the bounding box of all sections to properly size the room
    const sectionBounds = room.sections.reduce((acc, sec) => ({
        minX: Math.min(acc.minX, sec.posX * SCALE),
        minZ: Math.min(acc.minZ, sec.posY * SCALE),
        maxX: Math.max(acc.maxX, (sec.posX + sec.width) * SCALE),
        maxZ: Math.max(acc.maxZ, (sec.posY + sec.height) * SCALE),
    }), { minX: Infinity, minZ: Infinity, maxX: -Infinity, maxZ: -Infinity });

    // If we have sections, use their bounds for the room visualization
    const hasSections = room.sections.length > 0 && sectionBounds.minX !== Infinity;
    const actualRoom = hasSections ? {
        posX: sectionBounds.minX,
        posY: sectionBounds.minZ,
        width: sectionBounds.maxX - sectionBounds.minX,
        height: sectionBounds.maxZ - sectionBounds.minZ,
    } : scaledRoom;

    // Aggregated room data
    const roomAggregates = useMemo(() => {
        const totalPlants = room.sections.reduce((acc, sec) => acc + sec.positions.filter(p => p.plant).length, 0);
        const hash = room.name.split('').reduce((a, b) => a + b.charCodeAt(0), 0);
        const warnings = (hash % 10) > 8 ? 1 : 0;
        return { totalPlants, warnings };
    }, [room.name, room.sections]);

    return (
        <group>
            {/* Room Summary Badge Overlay */}
            <RoomSummaryOverlay
                roomName={room.name}
                plantCount={roomAggregates.totalPlants}
                warnings={roomAggregates.warnings}
                position={[actualRoom.posX + actualRoom.width / 2, 6, actualRoom.posY + actualRoom.height / 2]}
            />

            {/* Room label - positioned above the actual content area */}
            <Text
                position={[actualRoom.posX + actualRoom.width / 2, 0.05, actualRoom.posY + actualRoom.height / 2]}
                rotation={[-Math.PI / 2, 0, 0]}
                fontSize={Math.min(actualRoom.width, actualRoom.height) / 8}
                color="#f8fafc"
                fillOpacity={0.5}
                anchorX="center"
                anchorY="middle"
            >
                {room.name}
            </Text>

            {(visMode === 'TEMP' || visMode === 'HUMIDITY') && (
                <Text
                    position={[actualRoom.posX + actualRoom.width / 2, 4, actualRoom.posY + actualRoom.height / 2]}
                    rotation={[-Math.PI / 4, 0, 0]}
                    fontSize={Math.min(4, actualRoom.width / 4)}
                    color="#fff"
                    outlineColor="#000"
                    outlineWidth={0.15}
                    anchorX="center"
                >
                    {visMode === 'TEMP' ? `${env.temp}°F` : `${env.humidity}%`}
                </Text>
            )}

            {/* Room floor - use calculated bounds */}
            <mesh rotation={[-Math.PI / 2, 0, 0]} position={[actualRoom.posX + actualRoom.width / 2, -0.01, actualRoom.posY + actualRoom.height / 2]} receiveShadow>
                <planeGeometry args={[actualRoom.width + 1, actualRoom.height + 1]} />
                <meshStandardMaterial
                    color={floorColor}
                    roughness={0.95}
                    metalness={0.05}
                    transparent={true}
                    opacity={0.6}
                />
            </mesh>

            {/* Room boundary */}
            <lineSegments position={[actualRoom.posX + actualRoom.width / 2, 0.02, actualRoom.posY + actualRoom.height / 2]} rotation={[-Math.PI / 2, 0, 0]}>
                <edgesGeometry args={[new THREE.PlaneGeometry(actualRoom.width + 1, actualRoom.height + 1)]} />
                <lineBasicMaterial color="#64748b" />
            </lineSegments>

            {/* Sections are now positioned using their own absolute coordinates */}
            {room.sections.map(section => (
                <SmartRack
                    key={section.id}
                    section={section}
                    visMode={visMode}
                    onPlantClick={onPlantClick}
                    highlightedTags={highlightedTags}
                    dimMode={dimMode}
                    hierarchy={{ ...hierarchy, room: room.name }}
                    timelineDate={timelineDate}
                />
            ))}
        </group>
    );
}

