import { useState, useRef, useEffect, useCallback } from "react";
import { RoutePathAnimator } from "../utils/RoutePathAnimator";

interface RouteFollowingPositionState {
  x: number;
  y: number;
  isAnimating: boolean;
}

export const useRouteFollowingPosition = (defaultDuration: number = 800) => {
  const [position, setPosition] = useState<RouteFollowingPositionState>({
    x: 0,
    y: 0,
    isAnimating: false,
  });

  const animatorRef = useRef<RoutePathAnimator | null>(null);

  useEffect(() => {
    animatorRef.current = new RoutePathAnimator(
      (newPos) => {
        setPosition((prev) => ({ ...prev, x: newPos.x, y: newPos.y }));
      },
      () => {
        setPosition((prev) => ({ ...prev, isAnimating: false }));
      },
      defaultDuration,
    );

    return () => {
      animatorRef.current?.stop();
    };
  }, [defaultDuration]);

  const setRoutePath = useCallback(
    (path: Float32Array, syncMapXY?: { x: number; y: number }) => {
      animatorRef.current?.setRoutePath(path, syncMapXY);
    },
    [],
  );

  const animateTo = useCallback(
    (targetX: number, targetY: number, duration?: number) => {
      if (animatorRef.current) {
        setPosition((prev) => ({ ...prev, isAnimating: true }));
        animatorRef.current.animateTo(targetX, targetY, duration);
      }
    },
    [],
  );

  const setPositionImmediate = useCallback((x: number, y: number) => {
    animatorRef.current?.stop();
    animatorRef.current?.setPosition(x, y);
    setPosition({ x, y, isAnimating: false });
  }, []);

  const stopAnimation = useCallback(() => {
    animatorRef.current?.stop();
    setPosition((prev) => ({ ...prev, isAnimating: false }));
  }, []);

  const getCurrentSegIndex = useCallback((): number => {
    return animatorRef.current?.getCurrentSegIndex() ?? -1;
  }, []);

  return {
    position: { x: position.x, y: position.y },
    isAnimating: position.isAnimating,
    setRoutePath,
    animateTo,
    setPositionImmediate,
    stopAnimation,
    getCurrentSegIndex,
  };
};
