import React, { useEffect, useRef, useState } from "react";
import InputWithDropDown from "../../../../ui/inputs/InputWithDropDown";
import LabledDropdown from "../../../../ui/inputs/LabledDropdown";
import {
    AddIcon,
    RemoveIcon,
    ResizeHeightIcon,
} from "../../../../icons/ExportCommonIcons";
import RenameInput from "../../../../ui/inputs/RenameInput";
import { handleResize } from "../../../../../functions/handleResizePannel";
import { handleActionToggle } from "./functions/handleActionToggle";
import { handleDeleteAction } from "./functions/handleDeleteAction";
import DefaultAction from "./actions/DefaultAction";
import SpawnAction from "./actions/SpawnAction";
import SwapAction from "./actions/SwapAction";
import DespawnAction from "./actions/DespawnAction";
import TravelAction from "./actions/TravelAction";
import PickAndPlaceAction from "./actions/PickAndPlaceAction";
import ProcessAction from "./actions/ProcessAction";
import StorageAction from "./actions/StorageAction";
import Trigger from "./trigger/Trigger";

import { useSelectedEventData, useSelectedProduct } from "../../../../../store/simulation/useSimulationStore";
import { useProductStore } from "../../../../../store/simulation/useProductStore";
import ConveyorMechanics from "./mechanics/conveyorMechanics";
import VehicleMechanics from "./mechanics/vehicleMechanics";
import RoboticArmMechanics from "./mechanics/roboticArmMechanics";

const EventProperties: React.FC = () => {
    const actionsContainerRef = useRef<HTMLDivElement>(null);

    const [activeOption, setActiveOption] = useState("default");
    const [selectedItem, setSelectedItem] = useState<{ item: { uuid: string; name: string } | null; }>({ item: null });
    const { selectedEventData } = useSelectedEventData();
    const { getEventByModelUuid } = useProductStore();
    const { selectedProduct } = useSelectedProduct();

    // State for derived values
    const [currentEventData, setCurrentEventData] = useState<EventsSchema | null>(null);
    const [assetType, setAssetType] = useState<string | null>(null);
    const [availableActions, setAvailableActions] = useState({
        defaultOption: "default",
        options: ["default"]
    });
    const [actions, setActions] = useState<{ uuid: string; name: string }[]>([]);
    const [speed, setSpeed] = useState("0.5");

    useEffect(() => {
        const event = getCurrentEventData();
        setCurrentEventData(event);

        const type = determineAssetType(event);
        setAssetType(type);

        const actionsConfig = determineAvailableActions(type);
        setAvailableActions(actionsConfig);

        const actionList = getActionList(event, type);
        setActions(actionList);

        if (actionList.length > 0 && !selectedItem.item) {
            setSelectedItem({ item: actionList[0] });
        }

        const currentSpeed = getCurrentSpeed();
        setSpeed(currentSpeed);
    }, [selectedEventData, selectedProduct]);

    const getCurrentEventData = () => {
        if (!selectedEventData?.data || !selectedProduct) return null;
        return getEventByModelUuid(selectedProduct.productId, selectedEventData.data.modelUuid) || null;
    };

    const determineAssetType = (event: EventsSchema | null) => {
        if (!event) return null;

        switch (event.type) {
            case 'transfer': return 'conveyor';
            case 'vehicle': return 'vehicle';
            case 'roboticArm': return 'roboticArm';
            case 'machine': return 'machine';
            case 'storageUnit': return 'storageUnit';
            default: return null;
        }
    };

    const determineAvailableActions = (type: string | null) => {
        switch (type) {
            case "conveyor":
                return {
                    defaultOption: "default",
                    options: ["default", "spawn", "swap", "despawn"],
                };
            case "vehicle":
                return {
                    defaultOption: "travel",
                    options: ["travel"],
                };
            case "roboticArm":
                return {
                    defaultOption: "pickAndPlace",
                    options: ["pickAndPlace"],
                };
            case "machine":
                return {
                    defaultOption: "process",
                    options: ["process"],
                };
            case "storageUnit":
                return {
                    defaultOption: "store",
                    options: ["store", "spawn"],
                };
            default:
                return {
                    defaultOption: "default",
                    options: ["default"],
                };
        }
    };

    const getActionList = (event: EventsSchema | null, type: string | null) => {
        if (!selectedEventData?.data) return [];

        switch (type) {
            case "conveyor":
                return (event as ConveyorEventSchema).points
                    .find((point) => point.uuid === selectedEventData?.selectedPoint)
                    ?.action?.triggers.map((trigger) => ({
                        uuid: trigger.triggerUuid,
                        name: trigger.triggerName,
                    })) || [];
            case "vehicle":
                return (event as VehicleEventSchema).point.action.triggers.map(
                    (trigger) => ({
                        uuid: trigger.triggerUuid,
                        name: trigger.triggerName,
                    })
                ) || [];
            case "roboticArm":
                return (event as RoboticArmEventSchema).point.actions.flatMap(
                    (action) =>
                        action.triggers.map((trigger) => ({
                            uuid: trigger.triggerUuid,
                            name: trigger.triggerName,
                        }))
                ) || [];
            case "machine":
                return (event as MachineEventSchema).point.action.triggers.map(
                    (trigger) => ({
                        uuid: trigger.triggerUuid,
                        name: trigger.triggerName,
                    })
                ) || [];
            case "storageUnit":
                return [
                    {
                        uuid: (event as StorageEventSchema).point.action.actionUuid,
                        name: (event as StorageEventSchema).point.action.actionName,
                    },
                ];
            default:
                return [];
        }
    };

    const getCurrentSpeed = () => {
        if (!selectedEventData) return "0.5";
        if ("speed" in selectedEventData.data) return selectedEventData.data.speed.toString();
        return "0.5";
    };

    const handleActionToggle = (actionUuid: string) => {
        const selected = actions.find(action => action.uuid === actionUuid);
        if (selected) {
            setSelectedItem({ item: selected });
        }
    };

    const handleDeleteAction = (actionUuid: string) => {
        // Implementation for delete action
    };

    return (
        <>
            <div className="event-proprties-wrapper">
                {currentEventData &&
                    <>
                        <div className="header">
                            <div className="header-value">{selectedEventData?.data.modelName}</div>
                        </div>
                        <div className="global-props">
                            <div className="property-list-container">
                                <div className="property-item">
                                    <InputWithDropDown
                                        label="Speed"
                                        value="0.5"
                                        min={0}
                                        step={0.1}
                                        defaultValue={speed}
                                        max={10}
                                        activeOption="s"
                                        onClick={() => { }}
                                        onChange={(value) => console.log(value)}
                                    />
                                </div>

                                <div className="property-item">
                                    <InputWithDropDown
                                        label="Delay"
                                        value="0.5"
                                        min={0}
                                        step={0.1}
                                        defaultValue="0.5"
                                        max={10}
                                        activeOption="s"
                                        onClick={() => { }}
                                        onChange={(value) => console.log(value)}
                                    />
                                </div>
                            </div>
                        </div>
                        {assetType === 'roboticArm' &&
                            <div className="actions-list-container">
                                <div className="actions">
                                    <div className="header">
                                        <div className="header-value">Actions</div>
                                        <div className="add-button" onClick={() => { }}>
                                            <AddIcon /> Add
                                        </div>
                                    </div>
                                    <div
                                        className="lists-main-container"
                                        ref={actionsContainerRef}
                                        style={{ height: "120px" }}
                                    >
                                        <div className="list-container">
                                            {actions.map((action) => (
                                                <div
                                                    key={action.uuid}
                                                    className={`list-item ${selectedItem.item?.uuid === action.uuid ? "active" : ""}`}
                                                >
                                                    <div
                                                        className="value"
                                                        onClick={() => handleActionToggle(action.uuid)}
                                                    >
                                                        <RenameInput value={action.name} />
                                                    </div>
                                                    {actions.length > 1 && (
                                                        <div
                                                            className="remove-button"
                                                            onClick={() => handleDeleteAction(action.uuid)}
                                                        >
                                                            <RemoveIcon />
                                                        </div>
                                                    )}
                                                </div>
                                            ))}
                                        </div>
                                        <div
                                            className="resize-icon"
                                            id="action-resize"
                                            onMouseDown={(e) => handleResize(e, actionsContainerRef)}
                                        >
                                            <ResizeHeightIcon />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        }
                        <div className="selected-actions-details">
                            <div className="selected-actions-header">
                                <RenameInput value="Action Name" />
                            </div>
                            <div className="selected-actions-list">
                                <LabledDropdown
                                    defaultOption={availableActions.defaultOption}
                                    options={availableActions.options}
                                    onSelect={(option) => setActiveOption(option)}
                                />
                                {activeOption === "default" && <DefaultAction />}
                                {activeOption === "spawn" && <SpawnAction />}
                                {activeOption === "swap" && <SwapAction />}
                                {activeOption === "despawn" && <DespawnAction />}
                                {activeOption === "travel" && <TravelAction />}
                                {activeOption === "pickAndPlace" && <PickAndPlaceAction />}
                                {activeOption === "process" && <ProcessAction />}
                                {activeOption === "store" && <StorageAction />}
                            </div>
                        </div>
                        <div className="tirgger">
                            <Trigger />
                        </div>

                        {/* {assetType === 'conveyor' && <ConveyorMechanics />}
                        {assetType === 'vehicle' && <VehicleMechanics />}
                        {assetType === 'roboticArm' && <RoboticArmMechanics />} */}
                    </>
                }
            </div>
        </>
    );
};

export default EventProperties;