import { useEffect, useState } from 'react';
import * as THREE from 'three'
import { usePlayButtonStore } from '../../../../../store/usePlayButtonStore';
import { useSceneContext } from '../../../../scene/sceneContext';
import { useProductContext } from '../../../products/productContext';
import { useTriggerHandler } from '../../../triggers/triggerHandler/useTriggerHandler';

import PillarJibAnimator from '../animator/pillarJibAnimator'
import PillarJibHelper from '../helper/pillarJibHelper'
import MaterialAnimator from '../animator/materialAnimator';

function PillarJibInstance({ crane }: { crane: CraneStatus }) {
    const { isPlaying } = usePlayButtonStore();
    const { craneStore, productStore, humanStore, assetStore } = useSceneContext();
    const { triggerPointActions } = useTriggerHandler();
    const { getActionByUuid } = productStore();
    const { setCurrentPhase, setCraneActive, setIsCaryying, removeCurrentAction, removeLastMaterial, decrementCraneLoad } = craneStore();
    const { setCurrentPhase: setCurrentPhaseHuman, setHumanActive, setHumanState, getHumanById } = humanStore();
    const { setCurrentAnimation, getAssetById } = assetStore();
    const { selectedProductStore } = useProductContext();
    const { selectedProduct } = selectedProductStore();
    const [animationPhase, setAnimationPhase] = useState<string>('idle');
    const [points, setPoints] = useState<[THREE.Vector3, THREE.Vector3] | null>(null);
    const action = getActionByUuid(selectedProduct.productUuid, crane?.currentAction?.actionUuid || '');
    const actionTriggers = action?.triggers || [];
    const humanId = actionTriggers?.[0]?.triggeredAsset?.triggeredModel?.modelUuid ?? null;
    const humanAsset = getAssetById(humanId || '');
    const humanAction = getActionByUuid(selectedProduct.productUuid, actionTriggers?.[0]?.triggeredAsset?.triggeredAction?.actionUuid ?? '');

    useEffect(() => {
        if (isPlaying) {
            const human = getHumanById(humanId || '');
            if (!human || !humanAsset || !humanId || !action || action.actionType !== 'pickAndDrop') return;

            if (!crane.isActive && crane.currentPhase === 'init' && crane.currentMaterials.length > 0 && action.maxPickUpCount <= crane.currentMaterials.length) {
                setCurrentPhase(crane.modelUuid, 'init-pickup');
            } else if (crane.currentPhase === 'picking' && crane.currentMaterials.length > 0 && action.maxPickUpCount <= crane.currentMaterials.length && !crane.isCarrying) {
                if (humanAsset?.animationState?.current === "working_standing" && humanAsset?.animationState?.isCompleted && humanId && humanAction && humanAction.actionType === 'operator') {
                    setCurrentAnimation(humanId, 'idle', true, true, true);
                    setIsCaryying(crane.modelUuid, true);
                    setCurrentPhase(crane.modelUuid, 'pickup-drop');
                } else {
                    setCurrentPhaseHuman(humanId, 'hooking');
                    setHumanActive(humanId, true);
                    setHumanState(humanId, 'running');
                    setCurrentAnimation(humanId, 'working_standing', true, false, false);
                }
            } else if (crane.currentPhase === 'dropping' && crane.currentMaterials.length > 0 && action.maxPickUpCount <= crane.currentMaterials.length && crane.isCarrying && human.currentPhase === 'hooking') {
                setCurrentPhaseHuman(humanId, 'loadPoint-unloadPoint');
            } else if (human.state === 'running' && human.currentPhase === 'unhooking') {
                if (humanAsset?.animationState?.current === "working_standing" && humanAsset?.animationState?.isCompleted) {
                    setCurrentPhase(crane.modelUuid, 'init');
                    setCraneActive(crane.modelUuid, false);
                    setCurrentAnimation(humanId, 'idle', true, true, true);
                    setCurrentPhaseHuman(humanId, 'init');
                    setHumanActive(humanId, false);
                    setHumanState(humanId, 'idle');
                    handleMaterialDrop();
                }
            }
        }
    }, [crane, humanAsset?.animationState?.isCompleted])

    const handleMaterialDrop = () => {
        if (humanAction && humanAction.actionType === 'operator') {
            setIsCaryying(crane.modelUuid, false);
            removeCurrentAction(crane.modelUuid);
            const removedMaterial = removeLastMaterial(crane.modelUuid);
            decrementCraneLoad(crane.modelUuid, 1);

            if (removedMaterial && humanAction.triggers[0].triggeredAsset?.triggeredAction?.actionUuid) {
                triggerPointActions(humanAction, removedMaterial.materialId);
            }
        }
    }

    const handleAnimationComplete = (action: string) => {
        if (action === 'starting') {
            setAnimationPhase('first-hook-adjust');
        } else if (action === 'picking') {
            setCurrentPhase(crane.modelUuid, 'picking');
        } else if (action === 'dropping') {
            setCurrentPhase(crane.modelUuid, 'dropping');
        }
    }

    return (
        <>

            <PillarJibAnimator
                key={crane.modelUuid}
                crane={crane}
                points={points}
                setPoints={setPoints}
                animationPhase={animationPhase}
                setAnimationPhase={setAnimationPhase}
                onAnimationComplete={handleAnimationComplete}
            />

            <MaterialAnimator crane={crane} />

            <PillarJibHelper
                crane={crane}
                points={points}
                isHelperNeeded={false}
            />

        </>
    )
}

export default PillarJibInstance;