import { useEffect, useState } from "react";
import { MathUtils } from "three";
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 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 CraneMechanics() {
    const [activeOption, setActiveOption] = useState<"pickAndDrop">("pickAndDrop");
    const [selectedPointData, setSelectedPointData] = useState<CranePointSchema | undefined>();

    const { selectedEventData } = useSelectedEventData();
    const { productStore } = useSceneContext();
    const { getPointByUuid, 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) {
            const point = getPointByUuid(
                selectedProduct.productUuid,
                selectedEventData.data.modelUuid,
                selectedEventData.selectedPoint
            ) as CranePointSchema | undefined;

            if (point?.actions) {
                setSelectedPointData(point);

                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 handleAddAction = () => {
        if (!selectedEventData || !selectedPointData) return;

        const newAction = {
            actionUuid: MathUtils.generateUUID(),
            actionName: `Action ${selectedPointData.actions.length + 1}`,
            actionType: "pickAndDrop" as const,
            maxPickUpCount: 1,
            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: "pickAndDrop",
        options: ["pickAndDrop"],
    };

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

    return (
        <>
            <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}
                            />
                        </div>
                        <div className="tirgger">
                            <Trigger
                                selectedPointData={selectedPointData as any}
                                type={"RoboticArm"}
                            />
                        </div>
                    </div>
                )}
            </section>
        </>
    );
}

export default CraneMechanics