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

type MaterialAnimatorProps = {
    agvDetail: VehicleStatus;
};


const MaterialAnimator = ({ agvDetail }: MaterialAnimatorProps) => {
    const meshRef = useRef<any>(null!);
    const [hasLoad, setHasLoad] = useState(false);
    const { scene } = useThree();
    const offset = new THREE.Vector3(0, 0.85, 0);

    useEffect(() => {
        setHasLoad(agvDetail.currentLoad > 0);
    }, [agvDetail.currentLoad]);

    useFrame(() => {
        if (!hasLoad || !meshRef.current) return;

        const agvModel = scene.getObjectByProperty("uuid", agvDetail.modelUuid) as THREE.Object3D;
        if (agvModel) {
            const worldPosition = offset.clone().applyMatrix4(agvModel.matrixWorld);
            meshRef.current.position.copy(worldPosition);
            meshRef.current.rotation.copy(agvModel.rotation);
        }
    });

    return (
        <>
            {hasLoad && (
                <>
                    {agvDetail.currentMaterials.length > 0 &&
                        <MaterialModel
                            matRef={meshRef}
                            materialType={agvDetail.currentMaterials[0].materialType || 'Default material'}
                        />
                    }
                </>
            )}
        </>
    );
};


export default MaterialAnimator;
