import { useEffect, useState } from "react";
import { MathUtils } from "three";
import InputWithDropDown from "../../../../../ui/inputs/InputWithDropDown";
import RenameInput from "../../../../../ui/inputs/RenameInput";
import LabledDropdown from "../../../../../ui/inputs/LabledDropdown";
import Trigger from "../trigger/Trigger";
import { useSelectedEventData, useSelectedAction } from "../../../../../../store/simulation/useSimulationStore";
import PickAndPlaceAction from "../actions/PickAndPlaceAction";
import ActionsList from "../components/ActionsList";
import { upsertProductOrEventApi } from "../../../../../../services/simulation/products/UpsertProductOrEventApi";
import { useProductContext } from "../../../../../../modules/simulation/products/productContext";
import { useParams } from "react-router-dom";
import { useVersionContext } from "../../../../../../modules/builder/version/versionContext";
import { useSceneContext } from "../../../../../../modules/scene/sceneContext";

function RoboticArmMechanics() {
    const [activeOption, setActiveOption] = useState<"pickAndPlace">("pickAndPlace");
    const [speed, setSpeed] = useState("0.5");
    const [selectedPointData, setSelectedPointData] = useState<RoboticArmPointSchema | undefined>();

    const { selectedEventData } = useSelectedEventData();
    const { productStore } = useSceneContext();
    const { getPointByUuid, getEventByModelUuid, updateEvent, updateAction, addAction, removeAction } = productStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { selectedAction, setSelectedAction, clearSelectedAction } = useSelectedAction();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { projectId } = useParams();

    useEffect(() => {
        if (selectedEventData && selectedEventData.data.type === 'roboticArm') {
            const point = getPointByUuid(
                selectedProduct.productUuid,
                selectedEventData.data.modelUuid,
                selectedEventData.selectedPoint
            ) as RoboticArmPointSchema | undefined;

            if (point?.actions) {
                setSelectedPointData(point);
                setSpeed(
                    (getEventByModelUuid(
                        selectedProduct.productUuid,
                        selectedEventData.data.modelUuid
                    ) as RoboticArmEventSchema | undefined)?.speed?.toString() || "0.5"
                );

                if (point.actions.length > 0) {
                    const firstAction = point.actions[0];
                    setActiveOption(firstAction.actionType);
                    setSelectedAction(firstAction.actionUuid, firstAction.actionName);
                }
            }
        } else {
            clearSelectedAction();
        }
    }, [selectedEventData, selectedProduct]);

    const updateBackend = (
        productName: string,
        productUuid: string,
        projectId: string,
        eventData: EventsSchema
    ) => {
        upsertProductOrEventApi({
            productName,
            productUuid,
            projectId,
            eventDatas: eventData,
            versionId: selectedVersion?.versionId || "",
        });
    };

    const handleSpeedChange = (value: string) => {
        if (!selectedEventData) return;

        const numericValue = parseFloat(value);
        if (isNaN(numericValue)) return;

        setSpeed(value);
        const event = updateEvent(
            selectedProduct.productUuid,
            selectedEventData.data.modelUuid,
            { speed: numericValue }
        );

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productUuid,
                projectId || '',
                event
            );
        }
    };

    const handleClearPoints = () => {
        if (!selectedAction.actionId || !selectedPointData) return;

        const event = updateAction(
            selectedProduct.productUuid,
            selectedAction.actionId,
            {
                process: {
                    startPoint: null,
                    endPoint: null,
                },
            }
        );

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productUuid,
                projectId || '',
                event
            );
        }
    };

    const handleAddAction = () => {
        if (!selectedEventData || !selectedPointData) return;

        const newAction = {
            actionUuid: MathUtils.generateUUID(),
            actionName: `Action ${selectedPointData.actions.length + 1}`,
            actionType: "pickAndPlace" as const,
            process: {
                startPoint: null,
                endPoint: null,
            },
            triggers: [] as TriggerSchema[],
        };

        const event = addAction(
            selectedProduct.productUuid,
            selectedEventData.data.modelUuid,
            selectedEventData.selectedPoint,
            newAction
        );

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productUuid,
                projectId || '',
                event
            );
        }

        setSelectedPointData({
            ...selectedPointData,
            actions: [...selectedPointData.actions, newAction],
        });
        setSelectedAction(newAction.actionUuid, newAction.actionName);
    };

    const handleDeleteAction = (actionUuid: string) => {
        if (!selectedPointData) return;

        const event = removeAction(
            selectedProduct.productUuid,
            actionUuid
        );

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productUuid,
                projectId || '',
                event
            );
        }

        const index = selectedPointData.actions.findIndex(a => a.actionUuid === actionUuid);
        const newActions = selectedPointData.actions.filter(a => a.actionUuid !== actionUuid);

        setSelectedPointData({
            ...selectedPointData,
            actions: newActions,
        });

        if (selectedAction.actionId === actionUuid) {
            const nextAction = newActions[index] || newActions[index - 1];
            if (nextAction) {
                setSelectedAction(nextAction.actionUuid, nextAction.actionName);
            } else {
                clearSelectedAction();
            }
        }
    };

    const availableActions = {
        defaultOption: "pickAndPlace",
        options: ["pickAndPlace"],
    };

    const currentAction = selectedPointData?.actions.find(a => a.actionUuid === selectedAction.actionId);

    return (
        <>
            <div className="global-props section">
                <div className="property-list-container">
                    <div className="property-item">
                        <InputWithDropDown
                            label="Speed"
                            value={speed}
                            min={0}
                            step={0.1}
                            defaultValue="0.5"
                            max={10}
                            activeOption="m/s"
                            onClick={() => { }}
                            onChange={handleSpeedChange}
                        />
                    </div>
                </div>
            </div>
            <section>
                <ActionsList
                    selectedPointData={selectedPointData}
                    multipleAction
                    handleAddAction={handleAddAction}
                    handleDeleteAction={handleDeleteAction}
                />

                {selectedAction.actionId && currentAction && (
                    <div className="selected-actions-details">
                        <div className="selected-actions-header">
                            <RenameInput
                                value={selectedAction.actionName || ""}
                                canEdit={false}
                            />
                        </div>
                        <div className="selected-actions-list">
                            <LabledDropdown
                                defaultOption={activeOption}
                                options={availableActions.options}
                                onSelect={() => { }}
                                disabled={true}
                            />
                            <PickAndPlaceAction clearPoints={handleClearPoints} />
                        </div>
                        <div className="tirgger">
                            <Trigger
                                selectedPointData={selectedPointData as any}
                                type={"RoboticArm"}
                            />
                        </div>
                    </div>
                )}
            </section>
        </>
    );
}

export default RoboticArmMechanics;