import React, { useEffect, useState } from "react";
import { init as initRecastNavigation } from "@recast-navigation/core";
import { generateSoloNavMesh } from "@recast-navigation/generators";
import { DebugDrawer, getPositionsAndIndices } from "@recast-navigation/three";
import { useThree } from "@react-three/fiber";
import * as THREE from "three";
import * as Types from "../../../types/world/worldTypes";

interface NavMeshDetailsProps {
  setNavMesh: (navMesh: any) => void;
  groupRef: React.MutableRefObject<THREE.Group | null>;
  lines: Types.RefLines;
}

export default function NavMeshDetails({
  lines,
  setNavMesh,
  groupRef,
}: NavMeshDetailsProps) {
  const { scene } = useThree();

  useEffect(() => {
    const initializeNavigation = async () => {
      try {
        await initRecastNavigation();

        if (!groupRef.current || groupRef.current.children.length === 0) {
          return;
        }

        const meshes = groupRef?.current?.children as THREE.Mesh[];

        const [positions, indices] = getPositionsAndIndices(meshes);

        const cellSize = 0.35;
        const cellHeight = 0.7;
        const walkableRadius = 0.5;
        const { success, navMesh } = generateSoloNavMesh(positions, indices, {
          cs: cellSize,
          ch: cellHeight,
          walkableRadius: Math.round(walkableRadius / cellHeight),
        });

        if (!success || !navMesh) {
          return;
        }

        setNavMesh(navMesh);

        scene.children
          .filter((child) => child instanceof DebugDrawer)
          .forEach((child) => scene.remove(child));

        const debugDrawer = new DebugDrawer();
        debugDrawer.drawNavMesh(navMesh);
        // scene.add(debugDrawer);
      } catch (error) { }
    };

    initializeNavigation();
  }, [scene, groupRef, lines.current]);

  return null;
}
