import React, { useRef, useMemo, useCallback } from "react";
import { InfoIcon } from "../../../icons/ExportCommonIcons";
import InputWithDropDown from "../../../ui/inputs/InputWithDropDown";
import { useSelectedActionSphere, useSimulationStates, useSocketStore } from "../../../../store/store";
import * as Types from '../../../../types/world/worldTypes';
import LabledDropdown from "../../../ui/inputs/LabledDropdown";
import { setEventApi } from "../../../../services/factoryBuilder/assest/floorAsset/setEventsApt";

const StaticMachineMechanics: React.FC = () => {
    const { selectedActionSphere } = useSelectedActionSphere();
    const { simulationStates, setSimulationStates } = useSimulationStates();
    const { socket } = useSocketStore();

    const propertiesContainerRef = useRef<HTMLDivElement>(null);

    const { selectedPoint, connectedPointUuids } = useMemo(() => {
        if (!selectedActionSphere?.points?.uuid) return { selectedPoint: null, connectedPointUuids: [] };

        const staticMachinePaths = simulationStates.filter(
            (path): path is Types.StaticMachineEventsSchema => path.type === "StaticMachine"
        );

        const points = staticMachinePaths.find(
            (path) => path.points.uuid === selectedActionSphere.points.uuid
        )?.points;

        if (!points) return { selectedPoint: null, connectedPointUuids: [] };

        const connectedUuids: string[] = [];
        if (points.connections?.targets) {
            points.connections.targets.forEach(target => {
                connectedUuids.push(target.pointUUID);
            });
        }

        return {
            selectedPoint: points,
            connectedPointUuids: connectedUuids
        };
    }, [selectedActionSphere, simulationStates]);

    const updateBackend = async (updatedPath: Types.StaticMachineEventsSchema | undefined) => {
        if (!updatedPath) return;
        const email = localStorage.getItem("email");
        const organization = email ? email.split("@")[1].split(".")[0] : "";

        // await setEventApi(
        //     organization,
        //     updatedPath.modeluuid,
        //     { type: "Vehicle", points: updatedPath.points }
        // );

        const data = {
            organization: organization,
            modeluuid: updatedPath.modeluuid,
            eventData: { type: "StaticMachine", points: updatedPath.points }
        }

        socket.emit('v2:model-asset:updateEventData', data);
    }

    const handleActionUpdate = useCallback((updatedAction: Partial<Types.StaticMachineEventsSchema['points']['actions']>) => {
        if (!selectedActionSphere?.points?.uuid) return;

        const updatedPaths = simulationStates.map((path) => {
            if (path.type === "StaticMachine" && path.points.uuid === selectedActionSphere.points.uuid) {
                return {
                    ...path,
                    points: {
                        ...path.points,
                        actions: {
                            ...path.points.actions,
                            ...updatedAction
                        }
                    }
                };
            }
            return path;
        });

        const updatedPath = updatedPaths.find(
            (path): path is Types.StaticMachineEventsSchema =>
                path.type === "StaticMachine" &&
                path.points.uuid === selectedActionSphere.points.uuid
        );
        updateBackend(updatedPath);

        setSimulationStates(updatedPaths);
    }, [selectedActionSphere?.points?.uuid, simulationStates, setSimulationStates]);

    const handleBufferChange = useCallback((buffer: number) => {
        handleActionUpdate({ buffer });
    }, [handleActionUpdate]);

    const handleMaterialChange = useCallback((material: string) => {
        handleActionUpdate({ material });
    }, [handleActionUpdate]);

    const handleTriggerChange = useCallback((updatedTrigger: Partial<Types.StaticMachineEventsSchema['points']['triggers']>) => {
        if (!selectedActionSphere?.points?.uuid) return;

        const updatedPaths = simulationStates.map((path) => {
            if (path.type === "StaticMachine" && path.points.uuid === selectedActionSphere.points.uuid) {
                return {
                    ...path,
                    points: {
                        ...path.points,
                        triggers: {
                            ...path.points.triggers,
                            ...updatedTrigger
                        }
                    }
                };
            }
            return path;
        });

        const updatedPath = updatedPaths.find(
            (path): path is Types.StaticMachineEventsSchema =>
                path.type === "StaticMachine" &&
                path.points.uuid === selectedActionSphere.points.uuid
        );
        updateBackend(updatedPath);

        setSimulationStates(updatedPaths);
    }, [selectedActionSphere?.points?.uuid, simulationStates, setSimulationStates]);

    const handleTriggerTypeChange = useCallback((type: string) => {
        handleTriggerChange({ type });
    }, [handleTriggerChange]);

    return (
        <div className="machine-mechanics-container" key={selectedPoint?.uuid}>
            <div className="machine-mechanics-header">
                {selectedActionSphere?.path?.modelName || "Machine point not found"}
            </div>


            <div className="machine-mechanics-content-container">
                <div className="selected-properties-container" ref={propertiesContainerRef}>
                    <div className="properties-header">Machine Properties</div>

                    {selectedPoint && (
                        <>
                            <InputWithDropDown
                                key={`buffer-${selectedPoint.uuid}`}
                                label="Buffer Time"
                                value={selectedPoint.actions.buffer.toString()}
                                onChange={(value) => handleBufferChange(parseInt(value))}
                            />

                            <LabledDropdown
                                key={`material-${selectedPoint.uuid}`}
                                label="Material"
                                defaultOption={selectedPoint.actions.material}
                                onSelect={(value) => handleMaterialChange(value)}
                                options={["Inherit", "Crate", "Box"]}
                            />

                            <LabledDropdown
                                key={`trigger-type-${selectedPoint.uuid}`}
                                label="Trigger Type"
                                defaultOption={selectedPoint.triggers.type}
                                onSelect={(value) => handleTriggerTypeChange(value)}
                                options={["OnComplete", "OnStart"]}
                            />

                            {/* <LabeledButton
                                label="Reset"
                                value="Reset Settings"
                                onClick={() => {
                                    // Implement reset functionality if needed
                                }}
                            /> */}
                        </>
                    )}
                </div>

                <div className="footer">
                    <InfoIcon />
                    Configure machine interaction properties and triggers.
                </div>
            </div>
        </div>
    );
};

export default React.memo(StaticMachineMechanics);