import { setCookie } from "cookies-next/client";
import { add } from "date-fns";
import { motion } from "framer-motion";
import { Expand, Minimize2 } from "lucide-react";
import { usePathname } from "next/navigation";
import { useState } from "react";

import { ARMinimizableLinks } from "~/components/navbar/mobile-nav";
import { Button } from "~/components/ui/button";
import { cn } from "~/lib/utils";

export const SIDEBAR_COOKIE_NAME = "sidebar_minimized";
export const Sidebar = ({
	defaultOpen,
	isAdmin,
	className,
}: {
	defaultOpen: boolean;
	isAdmin: boolean;
	className?: string;
}) => {
	const pathname = usePathname();
	const [isAnimating, setIsAnimating] = useState(false);
	const [minimized, setMinimized] = useState(defaultOpen);

	const toggleSidebar = (v: boolean) => {
		setIsAnimating(true);
		setMinimized(v);
		setCookie(SIDEBAR_COOKIE_NAME, v.toString(), {
			expires: add(new Date(), { days: 30 }),
		});
		setTimeout(() => {
			setIsAnimating(false);
		}, 300);
	};

	return (
		<motion.nav
			animate={{ width: minimized ? 55 : 192 }}
			aria-label="Sidebar Menu"
			className={cn(
				"relative z-30 hidden h-auto w-48 shrink-0 space-y-4 border-muted border-r bg-background pt-3 md:block dark:border-muted-foreground/15",
				className,
				minimized && "cursor-pointer",
			)}
		>
			{minimized && (
				<button
					aria-label="Expand sidebar"
					className="absolute inset-0 z-50 cursor-pointer border-none bg-transparent p-0 hover:bg-black/2"
					onClick={(e) => {
						e.preventDefault();
						e.stopPropagation();
						toggleSidebar(false);
					}}
					type="button"
				/>
			)}
			<div
				className={cn(
					"flex h-8 items-center justify-between px-4",
					minimized && "justify-center px-0",
				)}
			>
				{!minimized && (
					<h4 className={cn("w-full font-semibold text-xl")}>Menu</h4>
				)}
				<Button
					aria-label="Toggle Sidebar"
					className="px-0 text-base hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0"
					onClick={() => toggleSidebar(!minimized)}
					variant="ghost"
				>
					{minimized ? <Expand /> : <Minimize2 />}
					<span className="sr-only">Toggle Menu</span>
				</Button>
			</div>
			<div className={cn("px-2 text-lg")}>
				<ARMinimizableLinks
					isAdmin={isAdmin}
					isAnimating={isAnimating}
					minimized={minimized}
					pathname={pathname}
				/>
			</div>
		</motion.nav>
	);
};
