import { useEffect, useRef } from "react";
import { useBackdropStore } from "../../context/zustand-store/appStore";
import Lottie from "lottie-react";
import { motion, AnimatePresence } from "framer-motion";
import waiting from "../../assets/animations/waiting.json";

const Backdrop: React.FC = () => {
  const { isOpen, closeBackdrop } = useBackdropStore();
  const backdropRef = useRef<HTMLDivElement>(null);

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Escape") {
      closeBackdrop();
      return;
    }
    e.preventDefault();
    e.stopPropagation();
  };

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
      setTimeout(() => {
        backdropRef.current?.focus();
      }, 100);
    } else {
      document.body.style.overflow = "";
    }

    return () => {
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          ref={backdropRef}
          key="backdrop"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm"
          onKeyDown={handleKeyDown}
          tabIndex={-1}
          autoFocus
        >
          <motion.div
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.8, opacity: 0 }}
            transition={{ type: "spring", stiffness: 200, damping: 20 }}
            className="flex flex-col items-center justify-center"
          >
            <div className="w-32 h-32">
              <Lottie animationData={waiting} loop={true} />
            </div>
            <p className="mt-4 text-white text-lg font-medium select-none">
              لطفا صبر کنید ...
            </p>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export default Backdrop;
