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 {
    useSelectedAction,
    useSelectedEventData,
} 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/products/UpsertProductOrEventApi";
import { useProductContext } from "../../../../../../modules/simulation/products/productContext";
import { useParams } from "react-router-dom";

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 { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { setSelectedAction, clearSelectedAction } = useSelectedAction();

    const { projectId } = useParams();

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

            if (point) {
                setSelectedPointData(point);
                setActiveOption(point.action.actionType as "travel");
                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,
        });
    };

    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 "travel";
        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 (!selectedPointData) return;
        const event = updateAction(
            selectedProduct.productUuid,
            selectedPointData.action.actionUuid,
            { actionName: newName }
        );

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

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

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

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

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

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

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

    // Get current values from store

    const currentSpeed =
        (
            getEventByModelUuid(
                selectedProduct.productUuid,
                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";

    function handleClearPoints() {

        if (!selectedEventData || !selectedPointData?.action.actionUuid) return;

        const event = updateAction(
            selectedProduct.productUuid, selectedPointData.action.actionUuid, {
            pickUpPoint: null,
            unLoadPoint: null,
            steeringAngle: 0,
        })

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

    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,
                                        }}
                                        clearPoints={handleClearPoints}
                                    // 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;
