import React, { useEffect, useMemo, useRef, useState } from 'react'
import * as THREE from 'three';
import MaterialAnimator from '../animator/materialAnimator';
import { useProductStore } from '../../../../../store/simulation/useProductStore';
import { useSelectedProduct } from '../../../../../store/simulation/useSimulationStore';
import { MaterialModel } from '../material/materialModel';
import { useThree } from '@react-three/fiber';
import { useAnimationPlaySpeed } from '../../../../../store/usePlayButtonStore';
import { useTriggerHandler } from '../../../triggers/triggerHandler/useTriggerHandler';

function MaterialInstance({ material }: { material: MaterialSchema }) {
    const matRef: any = useRef();
    const { scene } = useThree();
    const { getModelUuidByPointUuid, getPointByUuid, getEventByModelUuid, getActionByUuid, getTriggerByUuid, getActionByPointUuid } = useProductStore();
    const { selectedProduct } = useSelectedProduct();
    const { speed } = useAnimationPlaySpeed();
    const { triggerPointActions } = useTriggerHandler();

    const getWorldPositionFromScene = (pointUuid: string): THREE.Vector3 | null => {
        const pointObj = scene.getObjectByProperty("uuid", pointUuid);
        if (!pointObj) return null;

        const worldPosition = new THREE.Vector3();
        pointObj.getWorldPosition(worldPosition);
        return worldPosition;
    };

    const { position, rotation, currentSpeed } = useMemo(() => {
        if (!material.current?.pointUuid) {
            return { position: new THREE.Vector3(0, 0, 0), rotation: new THREE.Vector3(0, 0, 0), currentSpeed: 1 };
        }

        const modelUuid = getModelUuidByPointUuid(selectedProduct.productId, material.current.pointUuid);
        if (!modelUuid) {
            return { position: new THREE.Vector3(0, 0, 0), rotation: new THREE.Vector3(0, 0, 0), currentSpeed: 1 };
        }

        const currentSpeed = getCurrentSpeed(selectedProduct.productId, modelUuid);

        const point = getPointByUuid(selectedProduct.productId, modelUuid, material.current.pointUuid);
        if (!point) {
            return { position: new THREE.Vector3(0, 0, 0), rotation: new THREE.Vector3(0, 0, 0), currentSpeed: currentSpeed || 1 };
        }

        const position = getWorldPositionFromScene(point.uuid);
        if (position) {
            return { position: position, rotation: new THREE.Vector3(0, 0, 0), currentSpeed: currentSpeed || 1 };
        }

        return {
            position: new THREE.Vector3(...point.position),
            rotation: new THREE.Vector3(...point.rotation),
            currentSpeed: currentSpeed || 1
        };
    }, [material, getPointByUuid]);


    function getCurrentSpeed(productId: string, modelUuid: string) {
        const event = getEventByModelUuid(productId, modelUuid)
        if (event) {
            if (event.type === 'transfer') {
                return event.speed;
            }

            if (event.type === 'vehicle') {
                return event.speed;
            }

            if (event.type === 'machine') {
                return 1;
            }

            if (event.type === 'roboticArm') {
                return event.speed;
            }

            if (event.type === 'storageUnit') {
                return 1;
            }

        } else {
            return 1;
        }
    }

    const callTrigger = () => {
        if (!material.next) return;
        const action = getActionByPointUuid(selectedProduct.productId, material.next.pointUuid);
        if (action) {
            triggerPointActions(action, material.materialId);
        }
    }

    return (
        <>

            {material.isRendered &&
                <MaterialModel matRef={matRef} materialType={material.materialType} visible={material.isVisible} position={position} />
            }

            <MaterialAnimator
                matRef={matRef}
                material={material}
                currentSpeed={currentSpeed * speed}
                onAnimationComplete={() => { callTrigger() }}
            />
        </>
    )
}

export default MaterialInstance