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

const VehicleMechanics: React.FC = () => {
    const { selectedActionSphere } = useSelectedActionSphere();
    const { simulationPaths, setSimulationPaths } = useSimulationPaths();
    const { eyeDropMode, setEyeDropMode } = useEyeDropMode();
    const { editingPoint, setEditingPoint } = useEditingPoint();
    const { previewPosition, setPreviewPosition } = usePreviewPosition();

    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((position: { x: number, y: number }) => {
    }, [handleActionUpdate]);

    const handleEndPointChange = React.useCallback((position: { x: number, y: number }) => {
    }, [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]);

    const handleStartEyeDropClick = () => {
        setEditingPoint('start');
        setEyeDropMode(true);
    };

    const handleEndEyeDropClick = () => {
        setEditingPoint('end');
        setEyeDropMode(true);
    };

    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 && (
                        <>
                            <PositionInput
                                label="Start Point"
                                onChange={() => { }}
                                disabled={true}
                                value1={
                                    editingPoint === 'start' && previewPosition
                                        ? parseFloat(previewPosition.x.toFixed(4))
                                        : selectedPoint.actions.start && 'x' in selectedPoint.actions.start
                                            ? parseFloat(selectedPoint.actions.start.x.toFixed(4))
                                            : 0
                                }
                                value2={
                                    editingPoint === 'start' && previewPosition
                                        ? parseFloat(previewPosition.y.toFixed(4))
                                        : selectedPoint.actions.start && 'y' in selectedPoint.actions.start
                                            ? parseFloat(selectedPoint.actions.start.y.toFixed(4))
                                            : 0
                                }

                                isEyedrop={true}
                                handleEyeDropClick={handleStartEyeDropClick}
                            />

                            <PositionInput
                                label="End Point"
                                onChange={() => { }}
                                disabled={true}
                                value1={
                                    editingPoint === 'end' && previewPosition
                                        ? parseFloat(previewPosition.x.toFixed(4))
                                        : selectedPoint.actions.end && 'x' in selectedPoint.actions.end
                                            ? parseFloat(selectedPoint.actions.end.x.toFixed(4))
                                            : 0
                                }
                                value2={
                                    editingPoint === 'end' && previewPosition
                                        ? parseFloat(previewPosition.y.toFixed(4))
                                        : selectedPoint.actions.end && 'y' in selectedPoint.actions.end
                                            ? parseFloat(selectedPoint.actions.end.y.toFixed(4))
                                            : 0
                                }
                                isEyedrop={true}
                                handleEyeDropClick={handleEndEyeDropClick}
                            />

                            <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);