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';
import { Html } from '@react-three/drei';

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);
    const [htmlPosition, setHtmlPosition] = useState<[number, number, number]>([0, 0, 0]);
    const [htmlRotation, setHtmlRotation] = useState<[number, number, number]>([0, 0, 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);
            setHtmlPosition([worldPosition.x, worldPosition.y, worldPosition.z]);
            meshRef.current.rotation.copy(agvModel.rotation);
            setHtmlRotation([agvModel.rotation.x, agvModel.rotation.y, agvModel.rotation.z]);
        }
    });

    return (
        <>
            {hasLoad && (
                <>
                    <MaterialModel
                        matRef={meshRef}
                        materialType={agvDetail.materialType || 'Default material'}
                    />

                    <Html
                        position={htmlPosition}
                        rotation={htmlRotation}
                        style={{ backgroundColor: "pink", padding: "4px", borderRadius: "4px" }}
                    >
                        {agvDetail.currentLoad}
                    </Html>

                </>
            )}
        </>
    );
};


export default MaterialAnimator;
