"use client";

import {
  useEffect,
  useRef,
  useState,
  type ReactNode,
  type Dispatch,
  type SetStateAction,
} from "react";
import { motion, AnimatePresence } from "framer-motion";
import { cn } from "@/utils";
interface DropdownProps {
  title: ReactNode;
  children: ReactNode;
  className?: String;
  isOpen: boolean;
  setIsOpen: Dispatch<SetStateAction<boolean>>;
}

export const Dropdown: React.FC<DropdownProps> = ({
  title,
  children,
  isOpen,
  setIsOpen,
  className,
}) => {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const [openUpward, setOpenUpward] = useState(false);

  useEffect(() => {
    if (!isOpen || !menuRef.current || !buttonRef.current) return;

    const menuRect = menuRef.current.getBoundingClientRect();
    const buttonRect = buttonRef.current.getBoundingClientRect();
    const spaceBelow = window.innerHeight - buttonRect.bottom;
    const spaceAbove = buttonRect.top;

    setOpenUpward(spaceBelow < menuRect.height && spaceAbove > menuRect.height);
  }, [isOpen]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        menuRef.current &&
        !menuRef.current.contains(event.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [setIsOpen]);

  return (
    <div className="relative inline-block text-left">
      <button
        ref={buttonRef}
        onClick={() => setIsOpen((prev) => !prev)}
        // className="inline-flex items-center gap-2 p-2 md:px-4 rounded-lg shadow-sm transition"
        aria-haspopup="true"
        aria-expanded={isOpen}
        className="w-full"
      >
        {title}
      </button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            ref={menuRef}
            initial={{ opacity: 0, y: openUpward ? -8 : 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: openUpward ? -8 : 8 }}
            transition={{ duration: 0.2 }}
            role="menu"
            aria-orientation="vertical"
            className={cn(
              "absolute z-50 min-w-28 mt-2 rounded-lg shadow-lg bg-bodyBg dark:bg-mainBg py-2 px-4",
              openUpward ? "bottom-full mb-2" : "top-full mt-2",
              className
              //   i18n.language === "ar" ? "left-0" : "right-0"
            )}
          >
            {children}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};
