import React, { useEffect, useState } from "react";
import { useThree } from "@react-three/fiber";
import useModuleStore from "../../../store/useModuleStore";
import { useSimulationStates } from "../../../store/store";
import * as SimulationTypes from '../../../types/simulationTypes';
import { ArmbotInstances } from "./ArmBotInstances";

interface ArmBotState {
    uuid: string;
    position: [number, number, number];
    rotation: [number, number, number];
    status: string;
    material: string;
    triggerId: string;
    connections: {
        source: { modelUUID: string; pointUUID: string };
        targets: { modelUUID: string; pointUUID: string }[];
    };
    actions: { uuid: string; name: string; speed: number; processes: { triggerId: string; startPoint: string; endPoint: string }[]; };
    isActive?: boolean;
}

interface StaticMachineState {
    uuid: string;
    status: string;
    actions: { uuid: string; name: string; buffer: number; material: string; };
    machineTriggerId: string;
    connectedArmBot: string;
}

interface ArmBotProps {
    armBots: ArmBotState[];
    setArmBots: React.Dispatch<React.SetStateAction<ArmBotState[]>>;
    setStaticMachines: React.Dispatch<React.SetStateAction<StaticMachineState[]>>;
}

const ArmBot = ({ armBots, setArmBots, setStaticMachines }: ArmBotProps) => {
    const { activeModule } = useModuleStore();
    const { scene } = useThree();
    const { simulationStates } = useSimulationStates();

    useEffect(() => {
        const filtered = simulationStates.filter((s): s is SimulationTypes.ArmBotEventsSchema => s.type === "ArmBot");
        const initialStates: ArmBotState[] = filtered
            .filter(bot => bot.points.connections.targets.length > 0)
            .map(bot => ({
                uuid: bot.modeluuid,
                position: bot.position,
                rotation: bot.rotation,
                status: "idle",
                material: "default",
                triggerId: '',
                actions: bot.points.actions,
                connections: bot.points.connections
            }));
        setArmBots(initialStates);
    }, [simulationStates]);

    useEffect(() => {
        armBots.forEach((bot) => {
            const object = scene.getObjectByProperty("uuid", bot.uuid);
            if (object) {
                object.visible = activeModule !== "simulation";
            }
        });
    }, [scene, activeModule, armBots]);

    return (
        <>
            {activeModule === "simulation" &&
                armBots.map((bot, i) => (
                    <ArmbotInstances
                        key={i}
                        index={i}
                        armBot={bot}
                        setArmBots={setArmBots}
                        setStaticMachines={setStaticMachines}
                    />
                ))}
        </>
    );
};

export default ArmBot;
