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 [speed, setSpeed] = useState("0.5");
    const [actionName, setActionName] = useState("Action Name");
    const [material, setMaterial] = useState("Default material");
    const [spawnCount, setSpawnCount] = useState("1");
    const [spawnInterval, setSpawnInterval] = useState("1");
    const [delay, setDelay] = useState("0");
    const [selectedPointData, setSelectedPointData] = useState<ConveyorPointSchema | undefined>();

    const { selectedEventData } = useSelectedEventData();
    const { productStore } = useSceneContext();
    const { getPointByUuid, updateEvent, updateAction, getEventByModelUuid } = 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;

            const event = getEventByModelUuid(
                selectedProduct.productUuid,
                selectedEventData?.data.modelUuid
            ) as ConveyorEventSchema | undefined;

            if (point && "action" in point && event) {
                setSelectedPointData(point);
                setActiveOption(point.action.actionType);
                setActionName(point.action.actionName);
                setSpeed(event.speed?.toString() || "0.5");
                setMaterial(point.action.material || "Default material");
                setSpawnCount(point.action.spawnCount?.toString() || "1");
                setSpawnInterval(point.action.spawnInterval?.toString() || "1");
                setDelay(point.action.delay?.toString() || "0");
                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 handleSpeedChange = (value: string) => {
        if (!selectedEventData) return;

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

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

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

    const handleActionTypeChange = (option: string) => {
        if (!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 handleSpawnCountChange = (value: string) => {
        if (!selectedPointData) return;

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

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

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

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

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

        setSpawnInterval(value);
        const event = updateAction(
            selectedProduct.productUuid,
            selectedPointData.action.actionUuid,
            { spawnInterval: 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,
            { material: selectedMaterial }
        );

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

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

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

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

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

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

    return (
        <>
            <div key={selectedPointData?.uuid} 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} />

                <div className="selected-actions-details">
                    <div className="selected-actions-header">
                        <RenameInput
                            value={actionName}
                            canEdit={false}
                        />
                    </div>
                    <div className="selected-actions-list">
                        <LabledDropdown
                            defaultOption={activeOption}
                            options={availableActions.options}
                            onSelect={handleActionTypeChange}
                        />
                        {activeOption === "default" && <DefaultAction />}
                        {activeOption === "spawn" && (
                            <SpawnAction
                                onChangeCount={handleSpawnCountChange}
                                options={["Default material", "Material 1", "Material 2", "Material 3"]}
                                defaultOption={material}
                                onSelect={handleMaterialSelect}
                                onChangeInterval={handleSpawnIntervalChange}
                                intervalValue={spawnInterval}
                                countValue={spawnCount}
                                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={material}
                                onSelect={handleMaterialSelect}
                            />
                        )}
                        {activeOption === "despawn" && <DespawnAction />}
                        {activeOption === "delay" && (
                            <DelayAction
                                value={delay}
                                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;