import { useEffect, useRef, useState } from 'react'
import * as THREE from 'three';
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, useSelectedAction } from "../../../../../../store/simulation/useSimulationStore";
import { useProductStore } from "../../../../../../store/simulation/useProductStore";
import { AddIcon, RemoveIcon, ResizeHeightIcon } from '../../../../../icons/ExportCommonIcons'
import { handleResize } from '../../../../../../functions/handleResizePannel'
import PickAndPlaceAction from '../actions/PickAndPlaceAction'

function RoboticArmMechanics() {
    const actionsContainerRef = useRef<HTMLDivElement>(null);
    const [activeOption, setActiveOption] = useState<"default" | "pickAndPlace">("default");
    const [selectedPointData, setSelectedPointData] = useState<RoboticArmPointSchema | undefined>();
    const { selectedEventData } = useSelectedEventData();
    const { getPointByUuid, updateEvent, updateAction, addAction, removeAction } = useProductStore();
    const { selectedProduct } = useSelectedProduct();
    const { selectedAction, setSelectedAction, clearSelectedAction } = useSelectedAction();

    useEffect(() => {
        if (selectedEventData) {
            const point = getPointByUuid(
                selectedProduct.productId,
                selectedEventData.data.modelUuid,
                selectedEventData.selectedPoint
            ) as RoboticArmPointSchema | undefined;
            if (point) {
                setSelectedPointData(point);
                setActiveOption(point.actions[0].actionType as "default" | "pickAndPlace");
                if (point.actions.length > 0 && !selectedAction.actionId) {
                    setSelectedAction(point.actions[0].actionUuid, point.actions[0].actionName);
                }
            }
        } else {
            clearSelectedAction();
        }
    }, [selectedEventData, selectedProduct]);

    const handleActionSelect = (actionUuid: string, actionName: string) => {
        setSelectedAction(actionUuid, actionName);
    };

    const handleAddAction = () => {
        if (!selectedEventData || !selectedPointData) return;

        const newAction = {
            actionUuid: THREE.MathUtils.generateUUID(),
            actionName: `Action ${selectedPointData.actions.length + 1}`,
            actionType: "pickAndPlace" as "pickAndPlace",
            process: {
                startPoint: null,
                endPoint: null
            },
            triggers: [] as TriggerSchema[]
        };

        addAction(
            selectedProduct.productId,
            selectedEventData.data.modelUuid,
            selectedEventData.selectedPoint,
            newAction
        );

        const updatedPoint = {
            ...selectedPointData,
            actions: [...selectedPointData.actions, newAction]
        };
        setSelectedPointData(updatedPoint);
        setSelectedAction(newAction.actionUuid, newAction.actionName);
    };

    const handleDeleteAction = (actionUuid: string) => {
        if (!selectedPointData) return;

        removeAction(actionUuid);
        const newActions = selectedPointData.actions.filter(a => a.actionUuid !== actionUuid);

        const updatedPoint = {
            ...selectedPointData,
            actions: newActions
        };
        setSelectedPointData(updatedPoint);

        if (selectedAction.actionId === actionUuid) {
            if (newActions.length > 0) {
                setSelectedAction(newActions[0].actionUuid, newActions[0].actionName);
            } else {
                clearSelectedAction();
            }
        }
    };

    const handleRenameAction = (newName: string) => {
        if (!selectedAction.actionId) return;
        updateAction(
            selectedAction.actionId,
            { actionName: newName }
        );

        if (selectedPointData) {
            const updatedActions = selectedPointData.actions.map(action =>
                action.actionUuid === selectedAction.actionId
                    ? { ...action, actionName: newName }
                    : action
            );
            setSelectedPointData({
                ...selectedPointData,
                actions: updatedActions
            });
        }
    };

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

    const handlePickPointChange = (value: string) => {
        if (!selectedAction.actionId || !selectedPointData) return;
        const [x, y, z] = value.split(',').map(Number);

        updateAction(
            selectedAction.actionId,
            {
                process: {
                    startPoint: [x, y, z] as [number, number, number],
                    endPoint: selectedPointData.actions.find(a => a.actionUuid === selectedAction.actionId)?.process.endPoint || null
                }
            }
        );
    };

    const handlePlacePointChange = (value: string) => {
        if (!selectedAction.actionId || !selectedPointData) return;
        const [x, y, z] = value.split(',').map(Number);

        updateAction(
            selectedAction.actionId,
            {
                process: {
                    startPoint: selectedPointData.actions.find(a => a.actionUuid === selectedAction.actionId)?.process.startPoint || null,
                    endPoint: [x, y, z] as [number, number, number]
                }
            }
        );
    };

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

    const currentSpeed = selectedEventData?.data.type === "roboticArm"
        ? selectedEventData.data.speed.toString()
        : "0.5";

    const currentAction = selectedPointData?.actions.find(a => a.actionUuid === selectedAction.actionId);
    const currentPickPoint = currentAction?.process.startPoint
        ? `${currentAction.process.startPoint[0]},${currentAction.process.startPoint[1]},${currentAction.process.startPoint[2]}`
        : "";
    const currentPlacePoint = currentAction?.process.endPoint
        ? `${currentAction.process.endPoint[0]},${currentAction.process.endPoint[1]},${currentAction.process.endPoint[2]}`
        : "";

    return (
        <>
            {selectedEventData && selectedPointData && (
                <>
                    <div className="global-props">
                        <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>

                    <div className="actions-list-container">
                        <div className="actions">
                            <div className="header">
                                <div className="header-value">Actions</div>
                                <div className="add-button" onClick={handleAddAction}>
                                    <AddIcon /> Add
                                </div>
                            </div>
                            <div
                                className="lists-main-container"
                                ref={actionsContainerRef}
                                style={{ height: "120px" }}
                            >
                                <div className="list-container">
                                    {selectedPointData.actions.map((action) => (
                                        <div
                                            key={action.actionUuid}
                                            className={`list-item ${selectedAction.actionId === action.actionUuid ? "active" : ""}`}
                                        >
                                            <div
                                                className="value"
                                                onClick={() => handleActionSelect(action.actionUuid, action.actionName)}
                                            >
                                                <RenameInput
                                                    value={action.actionName}
                                                    onRename={handleRenameAction}
                                                />
                                            </div>
                                            {selectedPointData.actions.length > 1 && (
                                                <div
                                                    className="remove-button"
                                                    onClick={() => handleDeleteAction(action.actionUuid)}
                                                >
                                                    <RemoveIcon />
                                                </div>
                                            )}
                                        </div>
                                    ))}
                                </div>
                                <div
                                    className="resize-icon"
                                    id="action-resize"
                                    onMouseDown={(e) => handleResize(e, actionsContainerRef)}
                                >
                                    <ResizeHeightIcon />
                                </div>
                            </div>
                        </div>
                    </div>

                    {selectedAction.actionId && currentAction && (
                        <div className="selected-actions-details">
                            <div className="selected-actions-header">
                                <RenameInput
                                    value={selectedAction.actionName}
                                    onRename={handleRenameAction}
                                />
                            </div>
                            <div className="selected-actions-list">
                                <LabledDropdown
                                    defaultOption={activeOption}
                                    options={availableActions.options}
                                    onSelect={() => { }}
                                    disabled={true}
                                />
                                <PickAndPlaceAction
                                    pickPointValue={currentPickPoint}
                                    pickPointOnChange={handlePickPointChange}
                                    placePointValue={currentPlacePoint}
                                    placePointOnChange={handlePlacePointChange}
                                />
                            </div>
                            <div className="tirgger">
                                <Trigger />
                            </div>
                        </div>
                    )}
                </>
            )}
        </>
    )
}

export default RoboticArmMechanics