import { useEffect, useState } from "react";
import RenameInput from "../../../../../ui/inputs/RenameInput";
import LabledDropdown from "../../../../../ui/inputs/LabledDropdown";
import Trigger from "../trigger/Trigger";
import { useSelectedAction, useSelectedEventData } from "../../../../../../store/simulation/useSimulationStore";
import ProcessAction from "../actions/ProcessAction";
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 MachineMechanics() {
    const [activeOption, setActiveOption] = useState<"process">("process");
    const [actionName, setActionName] = useState("Action Name");
    const [processTime, setProcessTime] = useState("1");
    const [material, setMaterial] = useState("Default material");
    const [selectedPointData, setSelectedPointData] = useState<MachinePointSchema | undefined>();

    const { selectedEventData } = useSelectedEventData();
    const { productStore } = useSceneContext();
    const { getPointByUuid, updateAction } = productStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { 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 MachinePointSchema | undefined;

            if (point && "action" in point) {
                setSelectedPointData(point);
                setActiveOption(point.action.actionType as "process");
                setActionName(point.action.actionName);
                setProcessTime(point.action.processTime?.toString() || "1");
                setMaterial(point.action.swapMaterial || "Default material");
                setSelectedAction(point.action.actionUuid, point.action.actionName);
            }
        } else {
            clearSelectedAction();
        }
    }, [selectedProduct, selectedEventData]);

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

    const handleActionTypeChange = (option: string) => {
        if (!selectedPointData) return;

        const validOption = option as "process";
        setActiveOption(validOption);

        const event = updateAction(
            selectedProduct.productUuid,
            selectedPointData.action.actionUuid,
            { actionType: validOption }
        );

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

    const handleRenameAction = (newName: string) => {
        if (!selectedPointData) return;

        setActionName(newName);
        const event = updateAction(
            selectedProduct.productUuid,
            selectedPointData.action.actionUuid,
            { actionName: newName }
        );

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

    const handleProcessTimeChange = (value: string) => {
        if (!selectedPointData) return;

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

        setProcessTime(value);
        const event = updateAction(
            selectedProduct.productUuid,
            selectedPointData.action.actionUuid,
            { processTime: numericValue }
        );

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

    const handleMaterialSelect = (selectedMaterial: string) => {
        if (!selectedPointData) return;

        setMaterial(selectedMaterial);
        const event = updateAction(
            selectedProduct.productUuid,
            selectedPointData.action.actionUuid,
            { swapMaterial: selectedMaterial }
        );

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

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

    return (
        <>
            {selectedEventData && (
                <section>
                    <div className="selected-actions-details">
                        <div className="selected-actions-header">
                            <RenameInput
                                value={actionName}
                                canEdit={false}
                            />
                        </div>
                        <ActionsList selectedPointData={selectedPointData} />
                        <div className="selected-actions-list">
                            <LabledDropdown
                                defaultOption={activeOption}
                                options={availableActions.options}
                                onSelect={handleActionTypeChange}
                            />
                            {activeOption === "process" && (
                                <ProcessAction
                                    value={processTime}
                                    min={0.1}
                                    max={60}
                                    defaultValue="1"
                                    onChange={handleProcessTimeChange}
                                    swapOptions={["Default material", "Material 1", "Material 2", "Material 3"]}
                                    swapDefaultOption={material}
                                    onSwapSelect={handleMaterialSelect}
                                />
                            )}
                        </div>
                    </div>
                    <div className="tirgger">
                        <Trigger selectedPointData={selectedPointData as any} type={'Machine'} />
                    </div>
                </section>
            )}
        </>
    );
}

export default MachineMechanics;