import { createContext, useContext, useMemo } from 'react';
import { createMaterialStore, MaterialStoreType } from '../../store/simulation/useMaterialStore';
import { createArmBotStore, ArmBotStoreType } from '../../store/simulation/useArmBotStore';
import { createMachineStore, MachineStoreType } from '../../store/simulation/useMachineStore';
import { createConveyorStore, ConveyorStoreType } from '../../store/simulation/useConveyorStore';
import { createVehicleStore, VehicleStoreType } from '../../store/simulation/useVehicleStore';
import { createStorageUnitStore, StorageUnitStoreType } from '../../store/simulation/useStorageUnitStore';

type SceneContextValue = {
    materialStore: MaterialStoreType;
    armBotStore: ArmBotStoreType;
    machineStore: MachineStoreType;
    conveyorStore: ConveyorStoreType;
    vehicleStore: VehicleStoreType;
    storageUnitStore: StorageUnitStoreType;
    layout: 'Main Layout' | 'Comparison Layout';
};

const SceneContext = createContext<SceneContextValue | null>(null);

export function SceneProvider({
    children,
    layout
}: {
    readonly children: React.ReactNode;
    readonly layout: 'Main Layout' | 'Comparison Layout';
}) {
    const materialStore = useMemo(() => createMaterialStore(), []);
    const armBotStore = useMemo(() => createArmBotStore(), []);
    const machineStore = useMemo(() => createMachineStore(), []);
    const conveyorStore = useMemo(() => createConveyorStore(), []);
    const vehicleStore = useMemo(() => createVehicleStore(), []);
    const storageUnitStore = useMemo(() => createStorageUnitStore(), []);

    const contextValue = useMemo(() => (
        {
            materialStore,
            armBotStore,
            machineStore,
            conveyorStore,
            vehicleStore,
            storageUnitStore,
            layout
        }
    ), [materialStore, armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, layout]);

    return (
        <SceneContext.Provider value={contextValue}>
            {children}
        </SceneContext.Provider>
    );
}

// Base hook to get the context
export function useSceneContext() {
    const context = useContext(SceneContext);
    if (!context) {
        throw new Error('useSceneContext must be used within a SceneProvider');
    }
    return context;
}