import { useFrame } from '@react-three/fiber';
import { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { MaterialModel } from '../../../materials/instances/material/materialModel';

type MaterialAnimatorProps = {
    ikSolver: any;
    armBot: ArmBotStatus;
    currentPhase: string;
};

export default function MaterialAnimator({ ikSolver, armBot, currentPhase }: Readonly<MaterialAnimatorProps>) {
    const materialRef = useRef<any>(null);
    const [isRendered, setIsRendered] = useState<boolean>(false);

    useEffect(() => {
        if (currentPhase === "start-to-end" || currentPhase === "dropping") {
            setIsRendered(true);
        } else {
            setIsRendered(false);
        }
    }, [currentPhase]);

    useFrame(() => {
        if (!ikSolver || !materialRef.current) return;

        const boneTarget = ikSolver.mesh.skeleton.bones.find((b: any) => b.name === "Bone004");
        const bone = ikSolver.mesh.skeleton.bones.find((b: any) => b.name === "Effector");

        if (!boneTarget || !bone) return;

        if (currentPhase === "start-to-end") {
            // Get world positions
            const boneTargetWorldPos = new THREE.Vector3();
            const boneWorldPos = new THREE.Vector3();
            boneTarget.getWorldPosition(boneTargetWorldPos);
            bone.getWorldPosition(boneWorldPos);

            // Calculate direction
            const direction = new THREE.Vector3();
            direction.subVectors(boneWorldPos, boneTargetWorldPos).normalize();

            const adjustedPosition = boneWorldPos.clone().addScaledVector(direction, 0.01);

            //set position
            materialRef.current.position.copy(adjustedPosition);

            // Set rotation
            const worldQuaternion = new THREE.Quaternion();
            bone.getWorldQuaternion(worldQuaternion);
            materialRef.current.quaternion.copy(worldQuaternion);
        }
    });

    return (
        <>
            {isRendered && (
                <MaterialModel
                    materialId={armBot.currentAction?.materialId ?? ''}
                    matRef={materialRef}
                    materialType={armBot.currentAction?.materialType ?? 'Default material'}
                />
            )}
        </>
    );
}
