import PolygonGenerator from "./polygonGenerator";
import { useThree } from "@react-three/fiber";
import { useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import * as Types from "../../../types/world/worldTypes";
import PathNavigator from "./pathNavigator";
import NavMeshDetails from "./navMeshDetails";
import {
  useSelectedActionSphere,
  useSimulationPaths,
} from "../../../store/store";

const Agv = ({
  lines,
  plane,
}: {
  lines: Types.RefLines;
  plane: Types.RefMesh;
}) => {
  const [pathPoints, setPathPoints] = useState<
    {
      uuid: string;
      points: { x: number; y: number; z: number }[];
    }[]
  >([]);
  const { simulationPaths } = useSimulationPaths();
  const { selectedActionSphere } = useSelectedActionSphere();
  useEffect(() => {
    if (!Array.isArray(simulationPaths)) {
    } else {
      let agvModels = simulationPaths.filter(
        (val: any) => val.modelName === "agv"
      );

      let findMesh = agvModels.filter(
        (val: any) =>
          val.modeluuid === selectedActionSphere?.path?.modeluuid &&
          val.type === "Vehicle"
      );

      const result =
        findMesh.length > 0 &&
        findMesh[0].type === "Vehicle" &&
        typeof findMesh[0].point?.actions.start === "object" &&
        typeof findMesh[0].point?.actions.end === "object" &&
        "x" in findMesh[0].point.actions.start &&
        "y" in findMesh[0].point.actions.start &&
        "x" in findMesh[0].point.actions.end &&
        "y" in findMesh[0].point.actions.end
          ? [
              {
                uuid: findMesh[0].modeluuid, // Ensure it's a number

                points: [
                  {
                    x: findMesh[0].position[0],
                    y: findMesh[0].position[1],
                    z: findMesh[0].position[2],
                  },
                  {
                    x: findMesh[0].point.actions.start.x,
                    y: 0,
                    z: findMesh[0].point.actions.start.y,
                  },
                  {
                    x: findMesh[0].point.actions.end.x,
                    y: 0,
                    z: findMesh[0].point.actions.end.y,
                  },
                ],
              },
            ]
          : [];
      if (result.length > 0) {
        setPathPoints((prev) => {
          const existingUUIDs = new Set(prev.map((item) => item.uuid));
          const newItems = result.filter(
            (item) => !existingUUIDs.has(item.uuid)
          );
          return [...prev, ...newItems];
        });
      }
    }
  }, [simulationPaths, selectedActionSphere]);

  let groupRef = useRef() as Types.RefGroup;
  const [navMesh, setNavMesh] = useState();

  return (
    <>
      <PolygonGenerator groupRef={groupRef} lines={lines} plane={plane} />
      <NavMeshDetails
        lines={lines}
        setNavMesh={setNavMesh}
        groupRef={groupRef}
        plane={plane}
      />
      {pathPoints.map((pair, i) => (
        <PathNavigator
          navMesh={navMesh}
          selectedPoints={pair.points}
          id={pair.uuid}
          key={i}
        />
      ))}
      <group ref={groupRef} visible={false} name="Meshes"></group>
    </>
  );
};

export default Agv;
