import { PlantPosition } from './types';
import { Canvas } from '@react-three/fiber';
import { OrbitControls, Environment, ContactShadows } from '@react-three/drei';
import { RoomObject } from './RoomObject';
import { Room3D } from '../../lib/layoutApi';
import { useMemo } from 'react';

interface Room3DViewerProps {
    room: any;
    visMode?: 'STANDARD' | 'HEALTH' | 'YIELD' | 'TEMP' | 'HUMIDITY';
    onPlantClick?: (plant: PlantPosition) => void;
}

export function Room3DViewer({ room, visMode = 'STANDARD', onPlantClick }: Room3DViewerProps) {
    // Transform API room data to Room3D structure if needed
    const room3DData: Room3D = useMemo(() => {
        // If it already looks like a Room3D object (has racks/sections), use it.
        // Otherwise, construct a mock layout for visualization.
        if (room.racks || room.sections) {
            return {
                ...room,
                // Ensure dimensions exist
                width: room.width || 40, // Default to ~40ft
                height: room.height || 60,
                posX: room.x || 0, // Map x/y to posX/posY if needed, or default 0
                posY: room.y || 0,
                sections: room.sections || room.racks || [],
            };
        }

        // Fallback: Create a mock layout with some demo racks
        const mockWidth = 50;
        const mockHeight = 40;

        // Generate 4 mock racks
        const mockSections = Array.from({ length: 4 }).map((_, i) => ({
            id: `mock-rack-${i}`,
            name: `Rack 0${i + 1}`,
            type: 'rack',
            posX: 5 + (i * 10), // Spaced out X
            posY: 10,           // Centered Y roughly
            width: 4,
            height: 20,
            positions: Array.from({ length: 16 }).map((__, p) => ({
                id: `p-${i}-${p}`,
                name: `P${p + 1}`,
                valid: true
            }))
        }));

        return {
            id: room.id,
            name: room.name,
            type: room.type,
            width: mockWidth,
            height: mockHeight,
            posX: 0,
            posY: 0,
            sections: mockSections,
        };
    }, [room]);

    return (
        <div className="w-full h-[600px] bg-gradient-to-br from-slate-900 to-slate-950 rounded-2xl overflow-hidden border border-[var(--color-border-subtle)] relative">
            <Canvas
                shadows
                orthographic
                camera={{ position: [200, 200, 200], zoom: 30, near: -500, far: 1500 }}
                className="w-full h-full"
            >
                <ambientLight intensity={0.7} />
                <directionalLight position={[10, 50, 20]} intensity={1.5} castShadow />

                <group position={[0, -5, 0]}>
                    <RoomObject
                        room={room3DData}
                        visMode={visMode}
                        onPlantClick={onPlantClick || (() => { })}
                        highlightedTags={[]}
                        dimMode={false}
                        hierarchy={{
                            facility: 'Main',
                            building: 'A',
                            floor: '1',
                        }}
                    />
                </group>

                <ContactShadows position={[0, -5.01, 0]} opacity={0.3} scale={60} blur={2} far={20} />
                <Environment preset="city" />
                <OrbitControls
                    makeDefault
                    enableRotate={false}
                    enableZoom={true}
                    enablePan={true}
                />
            </Canvas>

            <div className="absolute bottom-4 right-4 bg-slate-900/90 backdrop-blur-md px-3 py-1.5 rounded-md border border-white/20 text-xs font-mono text-emerald-400 pointer-events-none shadow-xl">
                VIEW: ISOMETRIC // FIXED
            </div>
        </div>
    );
}
