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 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";
import { useVersionContext } from "../../../../../../modules/builder/version/versionContext";
import { useSceneContext } from "../../../../../../modules/scene/sceneContext";
import { useSelectedPath } from "../../../../../../store/builder/store";

function VehicleMechanics() {
    const [activeOption, setActiveOption] = useState<"travel">("travel");
    const [speed, setSpeed] = useState("0.5");
    const [actionName, setActionName] = useState("Action Name");
    const [loadCapacity, setLoadCapacity] = useState("1");
    const [unloadDuration, setUnloadDuration] = useState("1");
    const [selectedPointData, setSelectedPointData] = useState<VehiclePointSchema | undefined>();

    const { selectedEventData } = useSelectedEventData();
    const { productStore } = useSceneContext();
    const { getPointByUuid, updateEvent, updateAction, getEventByModelUuid } = productStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const { setSelectedAction, clearSelectedAction } = useSelectedAction();
    const { selectedVersionStore } = useVersionContext();
    const { selectedVersion } = selectedVersionStore();
    const { projectId } = useParams();
    const { setSelectedPath } = useSelectedPath();

    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");
                setActionName(point.action.actionName);
                setSpeed(
                    (getEventByModelUuid(
                        selectedProduct.productUuid,
                        selectedEventData.data.modelUuid
                    ) as VehicleEventSchema | undefined)?.speed?.toString() || "0.5"
                );
                setLoadCapacity(point.action.loadCapacity?.toString() || "1");
                setUnloadDuration(point.action.unLoadDuration?.toString() || "1");
                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;

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

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

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

        setActionName(newName);
        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 numericValue = parseFloat(value);
        if (isNaN(numericValue)) return;

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

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

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

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

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

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

    const handleClearPoints = () => {
        if (!selectedPointData) 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={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 === "travel" && (
                                    <TravelAction
                                        loadCapacity={{
                                            value: loadCapacity,
                                            min: 1,
                                            max: 100,
                                            defaultValue: "1",
                                            onChange: handleLoadCapacityChange,
                                        }}
                                        unloadDuration={{
                                            value: unloadDuration,
                                            min: 1,
                                            max: 60,
                                            defaultValue: "1",
                                            onChange: handleUnloadDurationChange,
                                        }}
                                        clearPoints={handleClearPoints}
                                    />
                                )}
                            </div>
                        </div>
                        <div className="tirgger">
                            <Trigger
                                selectedPointData={selectedPointData as any}
                                type={"Vehicle"}
                            />
                        </div>
                        <div style={{
                            display: "flex",
                            gap: "10px",
                            flexDirection: "column",
                            alignItems: "center"
                        }}>
                            <button
                                style={{
                                    backgroundColor: "#6f42c1",
                                    color: "#f3f3fd",
                                    borderRadius: "15px",
                                    height: "30px",
                                    width: "150px",
                                    border: "none",
                                    cursor: "pointer",
                                    padding: "0 5px",
                                }}
                                onClick={() => setSelectedPath("auto")}
                            >
                                Auto Generate Path
                            </button>
                            <button
                                style={{
                                    backgroundColor: "#6f42c1",
                                    color: "#f3f3fd",
                                    borderRadius: "15px",
                                    height: "30px",
                                    width: "150px",
                                    border: "none",
                                    cursor: "pointer",
                                    padding: "0 5px",
                                }}
                                onClick={() => setSelectedPath("manual")}
                            >
                                Create Path
                            </button>
                        </div>
                    </section>
                </>
            )}
        </>
    );
}

export default VehicleMechanics;