import { useEffect, useState } from "react";
import InputWithDropDown from "../../../../../ui/inputs/InputWithDropDown";
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 TravelAction from "../actions/TravelAction";
import ActionsList from "../components/ActionsList";
import { upsertProductOrEventApi } from "../../../../../../services/simulation/UpsertProductOrEventApi";

function VehicleMechanics() {
    const [activeOption, setActiveOption] = useState<"default" | "travel">("default");
    const [selectedPointData, setSelectedPointData] = useState<VehiclePointSchema | undefined>();
    const { selectedEventData } = useSelectedEventData();
    const { getPointByUuid, getEventByModelUuid, updateEvent, updateAction } = useProductStore();
    const { selectedProduct } = useSelectedProduct();

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

    useEffect(() => {
        if (selectedEventData && selectedEventData.data.type === 'vehicle') {
            const point = getPointByUuid(
                selectedProduct.productId,
                selectedEventData.data.modelUuid,
                selectedEventData.selectedPoint
            ) as VehiclePointSchema | undefined;

            if (point) {
                setSelectedPointData(point);
                setActiveOption(point.action.actionType as "travel");
            }
        }
    }, [selectedProduct, selectedEventData, getPointByUuid]);

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

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

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

    const handleActionTypeChange = (option: string) => {
        if (!selectedEventData || !selectedPointData) return;
        const validOption = option as "travel";
        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 handleLoadCapacityChange = (value: string) => {
        if (!selectedPointData) return;
        const event = updateAction(selectedProduct.productId, selectedPointData.action.actionUuid, {
            loadCapacity: parseFloat(value),
        });

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

    const handleUnloadDurationChange = (value: string) => {
        if (!selectedPointData) return;
        const event = updateAction(selectedProduct.productId, selectedPointData.action.actionUuid, {
            unLoadDuration: parseFloat(value),
        });

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

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

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

    // Get current values from store

    const currentSpeed = (getEventByModelUuid(
        selectedProduct.productId, selectedEventData?.data.modelUuid || ""
    ) as VehicleEventSchema | undefined)?.speed?.toString() || "0.5";

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

    const currentLoadCapacity = selectedPointData
        ? selectedPointData.action.loadCapacity.toString()
        : "1";

    const currentUnloadDuration = selectedPointData
        ? selectedPointData.action.unLoadDuration.toString()
        : "1";

    const currentPickPoint = selectedPointData?.action.pickUpPoint;

    const currentUnloadPoint = selectedPointData?.action.unLoadPoint;

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

    return (
        <>
            {selectedEventData && (
                <>
                    <div 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="travel"
                                    options={availableActions.options}
                                    onSelect={handleActionTypeChange}
                                />

                                {activeOption === "travel" && (
                                    <TravelAction
                                        loadCapacity={{
                                            value: currentLoadCapacity,
                                            min: 1,
                                            max: 100,
                                            defaultValue: "1",
                                            onChange: handleLoadCapacityChange,
                                        }}
                                        unloadDuration={{
                                            value: currentUnloadDuration,
                                            min: 1,
                                            max: 60,
                                            defaultValue: "1",
                                            onChange: handleUnloadDurationChange,
                                        }}
                                    // pickPoint={{
                                    //     value: currentPickPoint,
                                    //     onChange: handlePickPointChange,
                                    // }}
                                    // unloadPoint={{
                                    //     value: currentUnloadPoint,
                                    //     onChange: handleUnloadPointChange,
                                    // }}
                                    />
                                )}
                            </div>
                        </div>
                        <div className="tirgger">
                            <Trigger selectedPointData={selectedPointData as any} type= {'Vehicle'} />
                        </div>
                    </section>
                </>
            )}
        </>
    );
}

export default VehicleMechanics;
