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

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

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

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

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

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

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

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

  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 handleClearPoints = () => {
    if (!selectedAction.actionId || !selectedPointData) return;

    const event = updateAction(
      selectedProduct.productId,
      selectedAction.actionId,
      {
        process: {
          startPoint: null,
          endPoint: null,
        },
      }
    );

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

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

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

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

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

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

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

    const event = removeAction(selectedProduct.productId, actionUuid);

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

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

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

    if (selectedAction.actionId === actionUuid) {
      const nextAction = newActions[index] || newActions[index - 1];
      if (nextAction) {
        setSelectedAction(nextAction.actionUuid, nextAction.actionName);
      } else {
        clearSelectedAction();
      }
    }
  };

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

  const currentSpeed =
    (
      getEventByModelUuid(
        selectedProduct.productId,
        selectedEventData?.data.modelUuid || ""
      ) as RoboticArmEventSchema | undefined
    )?.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 (
    <>
      <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}
          multipleAction
          handleAddAction={handleAddAction}
          handleDeleteAction={handleDeleteAction}
        />

        {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 clearPoints={handleClearPoints} />
            </div>
            <div className="tirgger">
              <Trigger
                selectedPointData={selectedPointData as any}
                type={"RoboticArm"}
              />
            </div>
          </div>
        )}
      </section>
    </>
  );
}

export default RoboticArmMechanics;
