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';

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

    useEffect(() => {
        const loadState = agvDetail.currentLoad > 0;
        setHasLoad(loadState);
        
        if (!loadState) {
            setIsAttached(false);
            if (meshRef.current?.parent) {
                meshRef.current.parent.remove(meshRef.current);
            }
        }
    }, [agvDetail.currentLoad]);

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

        const agvModel = scene.getObjectByProperty("uuid", agvDetail.modelUuid) as THREE.Object3D;
        if (agvModel && !isAttached) {
            if (meshRef.current.parent) {
                meshRef.current.parent.remove(meshRef.current);
            }
            
            agvModel.add(meshRef.current);
            
            meshRef.current.position.copy(offset);
            meshRef.current.rotation.set(0, 0, 0);
            meshRef.current.scale.set(1, 1, 1);
            
            setIsAttached(true);
        }
    });

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

export default MaterialAnimator;