import { useEffect, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import { usePauseButtonStore, usePlayButtonStore, useResetButtonStore } from '../../../../store/usePlayButtonStore';
import { useSceneContext } from '../../../scene/sceneContext';

type VehicleCallback = {
    vehicleId: string;
    callback: () => void;
};

export function useVehicleEventManager() {
  const { vehicleStore } = useSceneContext();
    const { getVehicleById } = vehicleStore();
    const callbacksRef = useRef<VehicleCallback[]>([]);
    const isMonitoringRef = useRef(false);
    const { isPlaying } = usePlayButtonStore();
    const { isPaused } = usePauseButtonStore();
    const { isReset } = useResetButtonStore();

    useEffect(() => {
        if (isReset) {
            callbacksRef.current = [];
        }
    }, [isReset])

    // Add a new vehicle to monitor
    const addVehicleToMonitor = (vehicleId: string, callback: () => void) => {
        // Avoid duplicates
        if (!callbacksRef.current.some((entry) => entry.vehicleId === vehicleId)) {
            callbacksRef.current.push({ vehicleId, callback });
        }

        // Start monitoring if not already running
        if (!isMonitoringRef.current) {
            isMonitoringRef.current = true;
        }
    };

    // Remove a vehicle from monitoring
    const removeVehicleFromMonitor = (vehicleId: string) => {
        callbacksRef.current = callbacksRef.current.filter(
            (entry) => entry.vehicleId !== vehicleId
        );

        // Stop monitoring if no more vehicles to track
        if (callbacksRef.current.length === 0) {
            isMonitoringRef.current = false;
        }
    };

    // Check vehicle states every frame
    useFrame(() => {
        if (!isMonitoringRef.current || callbacksRef.current.length === 0 || !isPlaying || isPaused) return;

        callbacksRef.current.forEach(({ vehicleId, callback }) => {
            const vehicle = getVehicleById(vehicleId);
            if (vehicle && vehicle.isActive === false && vehicle.state === 'idle' && vehicle.isPicking && vehicle.currentLoad < vehicle.point.action.loadCapacity) {
                callback();
                removeVehicleFromMonitor(vehicleId); // Remove after triggering
            }
        });
    });

    // Cleanup on unmount
    useEffect(() => {
        return () => {
            callbacksRef.current = [];
            isMonitoringRef.current = false;
        };
    }, []);

    return {
        addVehicleToMonitor,
        removeVehicleFromMonitor,
    };
}