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);
	};
	//todo click to expand not working on direct links when minimized
	return (
		<motion.nav
			animate={{ width: minimized ? 55 : 192 }}
			aria-label="Sidebar Menu"
			className={cn(
				"z-30 hidden h-auto w-48 shrink-0 space-y-4 border-muted border-r bg-background pt-3 md:block",
				className,
				minimized && "cursor-pointer",
			)}
			onClick={
				minimized
					? (e) => {
							e.preventDefault();
							e.stopPropagation();
							toggleSidebar(false);
						}
					: undefined
			}
		>
			<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 className="size-5" />
					) : (
						<Minimize2 className="size-5" />
					)}
					<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>
	);
};
