import { useEffect, useState } from "react";
import InputWithDropDown from "../../../../../ui/inputs/InputWithDropDown";
import DelayAction from "../actions/DelayAction";
import RenameInput from "../../../../../ui/inputs/RenameInput";
import LabledDropdown from "../../../../../ui/inputs/LabledDropdown";
import DespawnAction from "../actions/DespawnAction";
import SwapAction from "../actions/SwapAction";
import SpawnAction from "../actions/SpawnAction";
import DefaultAction from "../actions/DefaultAction";
import Trigger from "../trigger/Trigger";
import { useSelectedAction, useSelectedEventData } 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 ConveyorMechanics() {
    const [activeOption, setActiveOption] = useState<"default" | "spawn" | "swap" | "delay" | "despawn">("default");
    const [selectedPointData, setSelectedPointData] = useState<ConveyorPointSchema | undefined>();
    const { selectedEventData } = useSelectedEventData();
    const { productStore } = useSceneContext();
    const { getPointByUuid, getEventByModelUuid, updateEvent, updateAction } = productStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { setSelectedAction, clearSelectedAction } = useSelectedAction();
    const { projectId } = useParams();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();

    useEffect(() => {
        if (selectedEventData) {
            const point = getPointByUuid(
                selectedProduct.productUuid,
                selectedEventData?.data.modelUuid,
                selectedEventData?.selectedPoint
            ) as ConveyorPointSchema | undefined;
            if (point && "action" in point) {
                setSelectedPointData(point);
                setActiveOption(point.action.actionType as | "default" | "spawn" | "swap" | "delay" | "despawn");
                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,
            versionId: selectedVersion?.versionId || '',
        })
    }

    const handleSpeedChange = (value: string) => {
        if (!selectedEventData) return;
        const event = updateEvent(selectedProduct.productUuid, selectedEventData.data.modelUuid, {
            speed: parseFloat(value),
        });

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

    const handleActionTypeChange = (option: string) => {
        if (!selectedEventData || !selectedPointData) return;
        const validOption = option as | "default" | "spawn" | "swap" | "delay" | "despawn";
        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 (!selectedEventData || !selectedPointData) return;
        const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, { actionName: newName });

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

    const handleSpawnCountChange = (value: string) => {
        if (!selectedEventData || !selectedPointData) return;
        const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, {
            spawnCount: parseFloat(value),
        });

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

    const handleSpawnIntervalChange = (value: string) => {
        if (!selectedEventData || !selectedPointData) return;
        const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, {
            spawnInterval: parseFloat(value),
        });

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

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

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

    const handleDelayChange = (value: string) => {
        if (!selectedEventData || !selectedPointData) return;
        const event = updateAction(selectedProduct.productUuid, selectedPointData.action.actionUuid, {
            delay: parseFloat(value),
        });

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

    const availableActions = {
        defaultOption: "default",
        options: ["default", "spawn", "swap", "delay", "despawn"],
    };

    // Get current values from store
    const currentSpeed = (getEventByModelUuid(
        selectedProduct.productUuid, selectedEventData?.data.modelUuid || ""
    ) as ConveyorEventSchema | undefined)?.speed?.toString() || "0.5";

    const currentActionName = selectedPointData
        ? selectedPointData.action.actionName
        : "Action Name";

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

    const currentSpawnCount = selectedPointData
        ? selectedPointData.action.spawnCount?.toString() || "1"
        : "1";

    const currentSpawnInterval = selectedPointData
        ? selectedPointData.action.spawnInterval?.toString() || "1"
        : "1";

    const currentDelay = selectedPointData
        ? selectedPointData.action.delay?.toString() || "0"
        : "0";

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

                <div className="selected-actions-details">
                    <div className="selected-actions-header">
                        <RenameInput
                            value={currentActionName}
                            onRename={handleRenameAction}
                        />
                    </div>
                    <div className="selected-actions-list">
                        <LabledDropdown
                            defaultOption={
                                selectedPointData
                                    ? selectedPointData.action.actionType
                                    : "default"
                            }
                            options={availableActions.options}
                            onSelect={handleActionTypeChange}
                        />
                        {activeOption === "default" && <DefaultAction />}
                        {activeOption === "spawn" && (
                            <SpawnAction
                                onChangeCount={handleSpawnCountChange}
                                options={["Default material", "Material 1", "Material 2", "Material 3"]}
                                defaultOption={currentMaterial}
                                onSelect={handleMaterialSelect}
                                onChangeInterval={handleSpawnIntervalChange}
                                intervalValue={currentSpawnInterval}
                                countValue={currentSpawnCount}
                                intervalMin={1}
                                intervalMax={60}
                                intervalDefaultValue="1"
                                countMin={1}
                                countMax={100}
                                countDefaultValue="1"
                            />
                        )}
                        {activeOption === "swap" && (
                            <SwapAction
                                options={["Default material", "Material 1", "Material 2", "Material 3"]}
                                defaultOption={currentMaterial}
                                onSelect={handleMaterialSelect}
                            />
                        )}
                        {activeOption === "despawn" && <DespawnAction />}
                        {activeOption === "delay" && (
                            <DelayAction
                                value={currentDelay}
                                defaultValue="0"
                                min={0}
                                max={60}
                                onChange={handleDelayChange}
                            />
                        )}
                    </div>
                </div>
                <div className="tirgger">
                    <Trigger selectedPointData={selectedPointData as any} type={'Conveyor'} />
                </div>
            </section>
        </>
    );
}

export default ConveyorMechanics;
