import { useEffect, useMemo, useRef } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useLocation, useOutlet } from "react-router-dom";
import { getAppTabIndex } from "../navigation";

const pageTransition = {
  duration: 0.22,
  ease: [0.22, 1, 0.36, 1],
} as const;

export function AnimatedOutlet() {
  const location = useLocation();
  const outlet = useOutlet();
  const isPublicChatPage = location.pathname === "/public-chat";
  const isEditProfilePage = location.pathname === "/edit-profile";
  const reduceMotion = useReducedMotion();
  const previousPathRef = useRef(location.pathname);
  const pageRef = useRef<HTMLDivElement | null>(null);

  const direction = useMemo(() => {
    const currentPath = location.pathname;
    const previousPath = previousPathRef.current;
    const previousIndex = getAppTabIndex(previousPath);
    const currentIndex = getAppTabIndex(currentPath);

    if (previousIndex !== -1 && currentIndex !== -1) {
      return currentIndex > previousIndex ? 1 : currentIndex < previousIndex ? -1 : 0;
    }

    return 0;
  }, [location.pathname]);

  useEffect(() => {
    previousPathRef.current = location.pathname;
    pageRef.current?.scrollTo({ top: 0, behavior: "auto" });
  }, [location.pathname]);

  const initial = reduceMotion
    ? { opacity: 0 }
    : direction === 0
      ? { opacity: 0, y: 12, scale: 0.98 }
      : { opacity: 0, x: direction * 32, scale: 0.98 };

  const animate = reduceMotion
    ? { opacity: 1 }
    : direction === 0
      ? { opacity: 1, y: 0, scale: 1 }
      : { opacity: 1, x: 0, scale: 1 };

  const exit = reduceMotion
    ? { opacity: 0 }
    : direction === 0
      ? { opacity: 0, y: -8, scale: 0.98 }
      : { opacity: 0, x: direction * -32, scale: 0.98 };

  return (
    <div className="page-frame">
      <AnimatePresence mode="wait" initial={false}>
        <motion.div
          key={location.pathname}
          className="page"
          ref={pageRef}
          initial={initial}
          animate={animate}
          exit={exit}
          transition={{
            ...pageTransition,
            duration: reduceMotion ? 0.12 : pageTransition.duration,
          }}
          style={
            isPublicChatPage
              ? {
                  willChange: "opacity, transform",
                  overflowY: "hidden",
                  paddingLeft: "0px",
                  paddingRight: "0px",
                  paddingBottom: "0px",
                }
              : isEditProfilePage
                ? {
                    willChange: "opacity, transform",
                    paddingBottom: "0px",
                  }
              : { willChange: "opacity, transform" }
          }
        >
          {outlet}
        </motion.div>
      </AnimatePresence>
    </div>
  );
}
