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

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, setOffset] = useState(new Vector3(0, 0.85, 0));

    useEffect(() => {
        const loadState = agvDetail.currentLoad > 0;
        setHasLoad(loadState);

        if (!loadState) {
            setIsAttached(false);
            const agvModel = scene.getObjectByProperty("uuid", agvDetail.modelUuid) as Object3D;
            if (agvModel) {
                // update offset
                let offsetY = agvDetail?.point.position[1];
                if(offsetY) setOffset(new Vector3(0, offsetY, 0));

                const material = agvModel.getObjectByName('Sample-Material');
                if (material) {
                    agvModel.remove(material);
                }
            }
        }
        // eslint-disable-next-line
    }, [agvDetail.currentLoad]);

    useFrame(() => {
        // if (agvDetail.currentMaterials.length === 0 || agvDetail.currentLoad === 0) {
        //     const agvModel = scene.getObjectByProperty("uuid", agvDetail.modelUuid) as Object3D;
        //     if (agvModel) {
        //         const material = agvModel.getObjectByName('Sample-Material');
        //         if (material) {
        //             agvModel.remove(material);
        //         }
        //     }
        // }
        if (!hasLoad || !meshRef.current || isAttached) return;

        const agvModel = scene.getObjectByProperty("uuid", agvDetail.modelUuid) as Object3D;
        if (agvModel && !isAttached) {
            const material = agvModel.getObjectByName('Sample-Material');
            if (material) {
                agvModel.remove(material);
            }

            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
                    name={'Sample-Material'}
                    matRef={meshRef}
                    materialId={agvDetail.currentMaterials[0].materialId || ''}
                    materialType={agvDetail.currentMaterials[0].materialType || 'Default material'}
                    visible={isAttached}
                />
            )}
        </>
    );
};

export default MaterialAnimator;