import React, { useRef, useMemo } from "react";
import { InfoIcon } from "../../../icons/ExportCommonIcons";
import InputWithDropDown from "../../../ui/inputs/InputWithDropDown";
import { useSelectedActionSphere, useSimulationPaths } from "../../../../store/store";
import * as Types from '../../../../types/world/worldTypes';
import LabledDropdown from "../../../ui/inputs/LabledDropdown";

const VehicleMechanics: React.FC = () => {
    const { selectedActionSphere } = useSelectedActionSphere();
    const { simulationPaths, setSimulationPaths } = useSimulationPaths();

    const propertiesContainerRef = useRef<HTMLDivElement>(null);

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

        const vehiclePaths = simulationPaths.filter(
            (path): path is Types.VehicleEventsSchema => path.type === "Vehicle"
        );

        const point = vehiclePaths.find(
            (path) => path.point.uuid === selectedActionSphere.point.uuid
        )?.point;

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

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

        return {
            selectedPoint: point,
            connectedPointUuids: connectedUuids
        };
    }, [selectedActionSphere, simulationPaths]);

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

        const updatedPaths = simulationPaths.map((path) => {
            if (path.type === "Vehicle" && path.point.uuid === selectedActionSphere.point.uuid) {
                return {
                    ...path,
                    point: {
                        ...path.point,
                        actions: {
                            ...path.point.actions,
                            ...updatedAction
                        }
                    }
                };
            }
            return path;
        });

        setSimulationPaths(updatedPaths);
    }, [selectedActionSphere?.point?.uuid, simulationPaths, setSimulationPaths]);

    const handleStartPointChange = React.useCallback((uuid: string) => {
        handleActionUpdate({ start: uuid });
    }, [handleActionUpdate]);

    const handleEndPointChange = React.useCallback((uuid: string) => {
        handleActionUpdate({ end: uuid });
    }, [handleActionUpdate]);

    const handleHitCountChange = React.useCallback((hitCount: number) => {
        handleActionUpdate({ hitCount });
    }, [handleActionUpdate]);

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

    const handleSpeedChange = React.useCallback((speed: number) => {
        if (!selectedActionSphere?.point?.uuid) return;

        const updatedPaths = simulationPaths.map((path) => {
            if (path.type === "Vehicle" && path.point.uuid === selectedActionSphere.point.uuid) {
                return {
                    ...path,
                    point: {
                        ...path.point,
                        speed: speed
                    }
                };
            }
            return path;
        });

        setSimulationPaths(updatedPaths);
    }, [selectedActionSphere?.point?.uuid, simulationPaths, setSimulationPaths]);

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

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

                    {selectedPoint && (
                        <>
                            <LabledDropdown
                                key={`start-${selectedPoint.uuid}`}
                                label="Start Point"
                                defaultOption={selectedPoint.actions.start || "Select start point"}
                                options={connectedPointUuids}
                                onSelect={handleStartPointChange}
                            />

                            <LabledDropdown
                                key={`end-${selectedPoint.uuid}`}
                                label="End Point"
                                defaultOption={selectedPoint.actions.end || "Select end point"}
                                options={connectedPointUuids}
                                onSelect={handleEndPointChange}
                            />

                            <InputWithDropDown
                                key={`hitcount-${selectedPoint.uuid}`}
                                label="Hit Count"
                                value={selectedPoint.actions.hitCount.toString()}
                                onChange={(value) => handleHitCountChange(parseInt(value))}
                            />

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

                            <InputWithDropDown
                                key={`speed-${selectedPoint.uuid}`}
                                label="Vehicle Speed"
                                value={selectedPoint.speed.toString()}
                                onChange={(value) => handleSpeedChange(parseFloat(value))}
                            />
                        </>
                    )}
                </div>

                <div className="footer">
                    <InfoIcon />
                    Configure vehicle's movement and interaction properties.
                </div>
            </div>
        </div>
    );
};

export default React.memo(VehicleMechanics);