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 { useSelectedEventData, useSelectedProduct } from "../../../../../../store/simulation/useSimulationStore";
import { useProductStore } from "../../../../../../store/simulation/useProductStore";

function ConveyorMechanics() {
    const [activeOption, setActiveOption] = useState<"default" | "spawn" | "swap" | "delay" | "despawn">("default");
    const [selectedPointData, setSelectedPointData] = useState<ConveyorPointSchema | undefined>();
    const { selectedEventData } = useSelectedEventData();
    const { getPointByUuid, updateEvent, updateAction } = useProductStore();
    const { selectedProduct } = useSelectedProduct();

    useEffect(() => {
        if (selectedEventData) {
            const point = getPointByUuid(
                selectedProduct.productId,
                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");
            }
        }
    }, [selectedProduct, selectedEventData])

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

    const handleActionTypeChange = (option: string) => {
        if (!selectedEventData || !selectedPointData) return;
        const validOption = option as "default" | "spawn" | "swap" | "delay" | "despawn";
        setActiveOption(validOption);

        updateAction(
            selectedPointData.action.actionUuid,
            { actionType: validOption }
        );
    };

    const handleRenameAction = (newName: string) => {
        if (!selectedPointData) return;
        updateAction(
            selectedPointData.action.actionUuid,
            { actionName: newName }
        );
    };

    const handleSpawnCountChange = (value: string) => {
        if (!selectedPointData) return;
        updateAction(
            selectedPointData.action.actionUuid,
            { spawnCount: value === "inherit" ? "inherit" : parseFloat(value) }
        );
    };

    const handleSpawnIntervalChange = (value: string) => {
        if (!selectedPointData) return;
        updateAction(
            selectedPointData.action.actionUuid,
            { spawnInterval: value === "inherit" ? "inherit" : parseFloat(value) }
        );
    };

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

    const handleDelayChange = (value: string) => {
        if (!selectedPointData) return;
        updateAction(
            selectedPointData.action.actionUuid,
            { delay: value === "inherit" ? "inherit" : parseFloat(value) }
        );
    };

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

    // Get current values from store
    const currentSpeed = selectedEventData?.data.type === "transfer"
        ? selectedEventData.data.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 (
        <>
            {selectedEventData &&
                <>
                    <div key={selectedPointData?.uuid} className="global-props">
                        <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>

                    <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"]}
                                    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"]}
                                    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 />
                    </div>
                </>
            }
        </>
    )
}

export default ConveyorMechanics