import { AnimatePresence, motion } from "framer-motion";
import React, { useEffect, type ReactNode } from "react";
import { useTheme } from "../../hooks/useTheme";
import { getBorderRadius } from "../../utils/getBorderRadius";
import { twMerge } from "../../utils/tailwindMerge";

export const SlideInPanel = ({
	children,
	isVisible,
	closePanel,
	cardClasses,
}: {
	children: ReactNode;
	isVisible: boolean;
	closePanel: () => void;
	cardClasses?: string;
}) => {
	const theme = useTheme();
	const cardStyle = twMerge(
		"bn-bg-layer-1 bn-max-h-full bn-flex bn-flex-col bn-absolute bn-bottom-0 bn-left-0 bn-w-full bn-overflow-y-auto bn-border bn-border-solid bn-border-b-none bn-border-primary",
		cardClasses,
	);

	// @fixme: multiple effects are being called on escape
	useEffect(() => {
		const handleKeyDown = (event: { key: string }) => {
			if (event.key === "Escape") {
				closePanel();
			}
		};

		document.addEventListener("keydown", handleKeyDown);

		return () => {
			document.removeEventListener("keydown", handleKeyDown);
		};
	}, [closePanel]);

	return (
		<AnimatePresence>
			{isVisible && (
				<motion.div
					initial={{ opacity: 0, y: 50 }}
					animate={{ opacity: 1, y: 0 }}
					exit={{ opacity: 0, y: 50 }}
					transition={{
						duration: 0.2,
					}}
					className="bn-backdrop-blur-md bn-absolute bn-w-full bn-h-full bn-top-0 bn-left-0 bn-border bn-border-solid bn-border-primary bn-z-10"
					style={{ borderRadius: getBorderRadius(theme.borderRadius) }}
					onClick={closePanel}
				>
					{/* biome-ignore lint/a11y/useKeyWithClickEvents: <explanation> */}
					<div
						onClick={(e) => e.stopPropagation()}
						className={cardStyle}
						style={{ borderRadius: getBorderRadius(theme.borderRadius) }}
					>
						{children}
					</div>
				</motion.div>
			)}
		</AnimatePresence>
	);
};
