import { useState, useRef, useEffect } from "react";
import Button from "./Button";
import MoreIcon from "../icons/MoreIcon";
import { AnimatePresence, motion } from "motion/react";

interface ActionsPopoverProps {
  options: {
    label: string;
    onClick: () => void;
    icon?: React.ReactNode;
    disabled?: boolean;
  }[];
}

export default function ActionsPopover({ options }: ActionsPopoverProps) {
  const [isOpened, setIsOpened] = useState(false);
  const [openUpwards, setOpenUpwards] = useState(false);
  const popoverRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const [menuHeight, setMenuHeight] = useState(0);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      if (
        popoverRef.current &&
        !popoverRef.current.contains(event.target as Node)
      ) {
        setIsOpened(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("touchstart", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("touchstart", handleClickOutside);
    };
  }, []);

  useEffect(() => {
    if (isOpened && buttonRef.current) {
      const buttonRect = buttonRef.current.getBoundingClientRect();
      const spaceBelow = window.innerHeight - buttonRect.bottom;
      const spaceAbove = buttonRect.top;
      setOpenUpwards(spaceBelow < menuHeight && spaceAbove > menuHeight);
    }
  }, [isOpened, menuHeight, options.length]);

  return (
    <div className="relative" ref={popoverRef}>
      <button
        ref={buttonRef}
        className="flex items-center justify-center gap-[0.139vw] size-[1.667vw] rounded-[0.556vw] text-[#CCCCCC] hover:text-[#7D7D7D] hover:bg-[#F3F3F3] active:text-[#141414] "
        onClick={() => setIsOpened(!isOpened)}
      >
        <div className="2xl:size-[1.111vw] size-4 2xl:rounded-[0.556vw] rounded-2xl">
          <MoreIcon />
        </div>
      </button>

      <AnimatePresence>
        {isOpened && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            ref={(el) => {
              setMenuHeight(el?.offsetHeight || 0);
            }}
            className={`absolute z-10 right-0 w-[13.333vw] bg-white rounded-[1.111vw] shadow-[0_4px_40px_0_rgba(15,16,17,0.1)] overflow-hidden ${
              openUpwards ? "bottom-[100%]" : "top-[100%]"
            }`}
          >
            {options.map((option) => (
              <Button
                variant="tertiary"
                className="p-[0.833vw] button-s w-full flex items-center !rounded-none !justify-start gap-[0.556vw]"
                key={option.label}
                onClick={option.onClick}
                disabled={option.disabled}
              >
                <div className="size-[1.111vw] ">{option.icon}</div>
                {option.label}
              </Button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
