import { useEffect } from 'react'
import * as THREE from "three";
import { useThree } from "@react-three/fiber";
import { CCDIKSolver, CCDIKHelper } from "three/examples/jsm/animation/CCDIKSolver";
import { usePlayButtonStore, useResetButtonStore } from '../../../../../store/usePlayButtonStore';

type IKInstanceProps = {
    setIkSolver: any
    armBot: ArmBotStatus;
};

function IKInstance({ setIkSolver, armBot }: IKInstanceProps) {
    const { scene } = useThree();
    const { isPlaying } = usePlayButtonStore();
    const { isReset } = useResetButtonStore();
    const targetBoneName = "Target";
    const skinnedMeshName = "link_0";

    useEffect(() => {
        let retryId: NodeJS.Timeout | null = null;

        const trySetup = () => {
            const targetMesh = scene?.getObjectByProperty("uuid", armBot.modelUuid);

            if (!targetMesh || !targetMesh.userData.iks || targetMesh.userData.iks.length < 1) {
                retryId = setTimeout(trySetup, 100);
                return;
            }

            const OOI: any = {};
            targetMesh.traverse((n: any) => {
                if (n.name === targetBoneName) OOI.Target_Bone = n;
                if (n.name === skinnedMeshName) OOI.Skinned_Mesh = n;
            });
            if (!OOI.Target_Bone || !OOI.Skinned_Mesh) return;

            const rawIks: IK[] = targetMesh.userData.iks;
            const iks = rawIks.map((ik) => ({
                target: ik.target,
                effector: ik.effector,
                links: ik.links.map((link) => ({
                    index: link.index,
                    enabled: link.enabled,
                    rotationMin: link.rotationMin ? new THREE.Vector3(...link.rotationMin) : undefined,
                    rotationMax: link.rotationMax ? new THREE.Vector3(...link.rotationMax) : undefined,
                    limitation: link.limitation ? new THREE.Vector3(...link.limitation) : undefined,
                })),
                minDistance: ik.minDistance,
                maxDistance: ik.maxDistance,
                maxheight: ik.maxheight,
                minheight: ik.minheight,
            }));

            const solver = new CCDIKSolver(OOI.Skinned_Mesh, iks);
            setIkSolver(solver);

            // const helper = new CCDIKHelper(OOI.Skinned_Mesh, iks, 0.05)
            // scene.add(helper);
        };

        trySetup();

        return () => {
            if (retryId) clearTimeout(retryId);
        };
    }, [isPlaying, isReset]);

    return (
        <>
        </>
    )
}

export default IKInstance;