import React, { useCallback, useEffect, useState } from 'react'
import VehicleAnimator from '../animator/vehicleAnimator'
import * as THREE from "three";
import { NavMeshQuery } from '@recast-navigation/core';
import { useNavMesh } from '../../../../../store/store';
import { usePlayButtonStore } from '../../../../../store/usePlayButtonStore';
import { useVehicleStore } from '../../../../../store/simulation/useVehicleStore';

function VehicleInstance({ agvDetails }: any) {
  const { navMesh } = useNavMesh();
  const { isPlaying } = usePlayButtonStore();
  const { setVehicleActive, setVehicleState } = useVehicleStore();
  const [currentPhase, setCurrentPhase] = useState<(string)>("stationed");
  const [path, setPath] = useState<[number, number, number][]>([]);

  const computePath = useCallback((start: any, end: any) => {


    try {
      const navMeshQuery = new NavMeshQuery(navMesh);
      const { path: segmentPath } = navMeshQuery.computePath(start, end);
      return (
        segmentPath?.map(
          ({ x, y, z }) => [x, y + 0.1, z] as [number, number, number]
        ) || []
      );
    } catch {
      return [];
    }
  }, [navMesh]);

  useEffect(() => {
    // const pickupToDropPath = computePath(pickup, drop);
    // const dropToPickupPath = computePath(drop, pickup);

    if (isPlaying) {
      if (!agvDetails.isActive && agvDetails.state == "idle" && currentPhase == "stationed") {
        const toPickupPath = computePath(new THREE.Vector3(agvDetails.position[0], agvDetails.position[1], agvDetails.position[2]), agvDetails.point.action.pickUpPoint);
        setPath(toPickupPath)
        setVehicleActive(agvDetails.modelUuid, true)
        setVehicleState(agvDetails.modelUuid, "running")
        setCurrentPhase("stationed-pickup")
        // 
      }
    }
  }, [agvDetails, currentPhase, path, isPlaying])

  function handleCallBack() {
    if (currentPhase === "stationed-pickup") {
      setVehicleActive(agvDetails.modelUuid, false)
      setVehicleState(agvDetails.modelUuid, "idle")
      setCurrentPhase("picking")
      setPath([])
    }
  }


  return (
    <>

      <VehicleAnimator path={path} handleCallBack={handleCallBack} currentPhase={currentPhase} agvUuid={agvDetails?.modelUuid} />

    </>
  )
}

export default VehicleInstance