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 { useProductStore } from "../../../../../../store/simulation/useProductStore";
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";

function MachineMechanics() {
    const [activeOption, setActiveOption] = useState<"default" | "process">("default");
    const [selectedPointData, setSelectedPointData] = useState<MachinePointSchema | undefined>();
    const { selectedEventData } = useSelectedEventData();
    const { getPointByUuid, updateAction } = useProductStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { setSelectedAction, clearSelectedAction } = useSelectedAction();

    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");
                setSelectedAction(point.action.actionUuid, point.action.actionName);
            }
        } else {
            clearSelectedAction();
        }
    }, [selectedProduct, selectedEventData]);

    const updateBackend = (
        productName: string,
        productUuid: string,
        projectId: string,
        eventData: EventsSchema
    ) => {
        upsertProductOrEventApi({
            productName: productName,
            productUuid: productUuid,
            projectId: projectId,
            eventDatas: eventData
        })
    }

    const handleActionTypeChange = (option: string) => {
        if (!selectedEventData || !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;
        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 event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, {
            processTime: parseFloat(value),
        });

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

    const handleMaterialSelect = (material: string) => {
        if (!selectedPointData) return;
        const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, {
            swapMaterial: material,
        });

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

    // Get current values from store
    const currentActionName = selectedPointData
        ? selectedPointData.action.actionName
        : "Action Name";

    const currentProcessTime = selectedPointData
        ? selectedPointData.action.processTime.toString()
        : "1";

    const currentMaterial = selectedPointData
        ? selectedPointData.action.swapMaterial
        : "Default material";

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

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

export default MachineMechanics;
