import React, { useEffect, useMemo } from "react";
import * as THREE from "three";
import { useThree } from "@react-three/fiber";
import { generateSoloNavMesh } from "@recast-navigation/generators";
import { init as initRecastNavigation } from "@recast-navigation/core";
import { DebugDrawer, getPositionsAndIndices } from "@recast-navigation/three";
import { useToggleView } from "../../../../store/builder/store";

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

const NAVMESH_CONFIG = {

    // cellSize: 0.2,
    // cellHeight: 0.7,
    // walkableRadius: 0.5,

    cellSize: 0.3,
    cellHeight: 0.7,
    walkableRadius: 0.7,
};

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

    const meshes = useMemo(() => {
        return groupRef.current?.children.filter((child): child is THREE.Mesh =>
            child instanceof THREE.Mesh
        ) || [];
    }, [groupRef.current?.children]);

    useEffect(() => {
        if (toggleView || meshes.length === 0) return;

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

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

                const { cellSize, cellHeight, walkableRadius } = NAVMESH_CONFIG;

                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) {
                console.error("Failed to initialize navigation:", error);
            }
        };

        initializeNavigation();
    }, [meshes, setNavMesh, toggleView, scene]);

    return null;
}
