import { useEffect, useRef, useState } from 'react';
import { useThree } from '@react-three/fiber';
import * as THREE from 'three';
import { MaterialModel } from '../../../materials/instances/material/materialModel';
import { useSceneContext } from '../../../../scene/sceneContext';
import { useProductContext } from '../../../products/productContext';

const MaterialAnimator = ({ human }: { human: HumanStatus; }) => {
    const { productStore } = useSceneContext();
    const { getActionByUuid } = productStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const meshRef = useRef<any>(null!);
    const [hasLoad, setHasLoad] = useState(false);
    const [isAttached, setIsAttached] = useState(false);
    const action = getActionByUuid(selectedProduct.productUuid, human?.currentAction?.actionUuid || '');
    const { scene } = useThree();

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

    useEffect(() => {
        if (!hasLoad || !meshRef.current) {
            setIsAttached(false);
            return;
        }

        const humanModel = scene.getObjectByProperty("uuid", human.modelUuid) as THREE.Object3D;
        if (!humanModel) return;

        meshRef.current.visible = false;

        const bone = humanModel.getObjectByName('PlaceObjectRefBone') as THREE.Bone;
        if (bone) {
            if (meshRef.current.parent) {
                meshRef.current.parent.remove(meshRef.current);
            }

            bone.add(meshRef.current);

            meshRef.current.position.set(0, 0, 0);
            meshRef.current.rotation.set(0, 0, 0);
            meshRef.current.scale.set(1, 1, 1);

            meshRef.current.visible = true;
            setIsAttached(true);
        }
    }, [hasLoad, human.modelUuid, scene, human.currentPhase]);

    return (
        <>
            {hasLoad && action && (action as HumanAction).actionType === 'worker' && human.currentMaterials.length > 0 && (human.currentPhase !== 'init-pickup' && human.currentPhase !== 'init-manufacture' && human.currentPhase !== 'drop-pickup') && (
                <MaterialModel
                    matRef={meshRef}
                    materialId={`human-${human.currentMaterials[0].materialId}` || ''}
                    materialType={human.currentMaterials[0].materialType || 'Default material'}
                    visible={isAttached}
                />
            )}
        </>
    );
};

export default MaterialAnimator;