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

type MaterialAnimatorProps = {
    crane: CraneStatus;
};

export default function MaterialAnimator({ crane }: Readonly<MaterialAnimatorProps>) {
    const materialRef = useRef<any>(null);
    const { scene } = useThree();
    const [isRendered, setIsRendered] = useState<boolean>(false);

    useEffect(() => {
        if (crane.isCarrying && (crane.currentPhase === 'pickup-drop' || crane.currentPhase === 'dropping')) {
            setIsRendered(true);
        } else {
            setIsRendered(false);
        }
    }, [crane.isCarrying, crane.currentPhase]);

    useFrame(() => {
        const craneModel = scene.getObjectByProperty('uuid', crane.modelUuid);
        if (!materialRef.current || !craneModel) return;

        const base = craneModel.getObjectByName('hook');
        if (!base) return;

        if (crane.isCarrying) {
            const boneWorldPos = new THREE.Vector3();
            base.getWorldPosition(boneWorldPos);

            const yOffset = -0.65;
            boneWorldPos.y += yOffset;

            materialRef.current.position.copy(boneWorldPos);

            materialRef.current.up.set(0, 1, 0);
            materialRef.current.lookAt(
                materialRef.current.position.clone().add(new THREE.Vector3(0, 0, 1))
            );
        }
    });

    return (
        <>
            {isRendered && (
                <MaterialModel
                    materialId={crane.currentAction?.materialId ?? ''}
                    matRef={materialRef}
                    materialType={crane.currentAction?.materialType ?? 'Default material'}
                />
            )}
        </>
    );
}
