import { useEffect, useState } from "react";
import RenameInput from "../../../../../ui/inputs/RenameInput";
import LabledDropdown from "../../../../../ui/inputs/LabledDropdown";
import Trigger from "../trigger/Trigger";
import { useSelectedEventData, useSelectedProduct } from "../../../../../../store/simulation/useSimulationStore";
import { useProductStore } from "../../../../../../store/simulation/useProductStore";
import StorageAction from "../actions/StorageAction";
import ActionsList from "../components/ActionsList";
import { upsertProductOrEventApi } from "../../../../../../services/simulation/UpsertProductOrEventApi";

function StorageMechanics() {
    const [activeOption, setActiveOption] = useState<"default" | "store" | "spawn">("default");
    const [selectedPointData, setSelectedPointData] = useState<StoragePointSchema | undefined>();
    const { selectedEventData } = useSelectedEventData();
    const { getPointByUuid, updateAction } = useProductStore();
    const { selectedProduct } = useSelectedProduct();

    const email = localStorage.getItem('email')
    const organization = (email!.split("@")[1]).split(".")[0];

    useEffect(() => {
        if (selectedEventData) {
            const point = getPointByUuid(
                selectedProduct.productId,
                selectedEventData?.data.modelUuid,
                selectedEventData?.selectedPoint
            ) as StoragePointSchema | undefined;
            if (point && "action" in point) {
                setSelectedPointData(point);
                setActiveOption(point.action.actionType as "store" | "spawn");
            }
        }
    }, [selectedProduct, selectedEventData, getPointByUuid]);

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

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

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

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productId,
                organization,
                event
            );
        }
    };

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

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productId,
                organization,
                event
            );
        }
    };

    const handleCapacityChange = (value: string) => {
        if (!selectedPointData) return;
        const event = updateAction(selectedProduct.productId, selectedPointData.action.actionUuid, {
            storageCapacity: parseInt(value),
        });

        if (event) {
            updateBackend(
                selectedProduct.productName,
                selectedProduct.productId,
                organization,
                event
            );
        }
    };

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

    const currentCapacity = selectedPointData
        ? selectedPointData.action.storageCapacity.toString()
        : "0";

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

    return (
        <>
            {selectedEventData && (
                <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={activeOption}
                                options={availableActions.options}
                                onSelect={handleActionTypeChange}
                            />
                            {activeOption === "store" && (
                                <StorageAction
                                    value={currentCapacity}
                                    defaultValue="0"
                                    min={0}
                                    max={20}
                                    onChange={handleCapacityChange}
                                />
                            )}
                            {activeOption === "spawn" && (
                                <div className="spawn-options">
                                    <p>Spawn configuration options would go here</p>
                                </div>
                            )}
                        </div>
                    </div>
                    <div className="tirgger">
                        <Trigger selectedPointData={selectedPointData as any} type= {'StorageUnit'} />
                    </div>
                </section>
            )}
        </>
    );
}

export default StorageMechanics;
