import { usePathname } from "next/navigation";
import { ARMinimizableLinks } from "~/components/navbar/mobile-nav";
import { cn } from "~/lib/utils";
import { Button } from "~/components/ui/button";
import { Expand, Minimize2 } from "lucide-react";
import { motion } from "framer-motion";
import { getCookie, setCookie } from "cookies-next/client";
import { useEffect, useState } from "react";
import { add } from "date-fns";

export const Sidebar = ({
  isAdmin,
  className,
}: {
  isAdmin: boolean;
  className?: string;
}) => {
  const pathname = usePathname();

  const [minimized, setMinimized] = useState(false);

  useEffect(() => {
    const defaultOpen = getCookie("sidebar_minimized") === "true";
    setMinimized(defaultOpen);
  }, []);
  const toggleSidebar = (v: boolean) => {
    setMinimized(v);
    setCookie("sidebar_minimized", v.toString(), {
      expires: add(new Date(), { days: 30 }),
    });
  };

  return (
    <motion.nav
      className={cn(
        "text-accent-foreground z-30 hidden h-auto w-48 shrink-0 space-y-4 border-r bg-white pt-3 md:block",
        className,
        minimized && "cursor-pointer",
        //defaultOpen && "w-[65px]",
      )}
      animate={{ width: minimized ? 65 : 192 }}
      onClick={
        minimized
          ? (e) => {
              e.preventDefault();
              e.stopPropagation();
              toggleSidebar(false);
            }
          : undefined
      }
      aria-label="Sidebar Menu"
    >
      <div
        className={cn(
          "flex items-center justify-between px-7",
          minimized && "justify-center px-0",
        )}
      >
        {!minimized && (
          <h4 className={cn("w-full text-xl font-semibold")}>Menu</h4>
        )}
        <Button
          aria-label="Toggle Sidebar"
          variant="ghost"
          onClick={() => toggleSidebar(!minimized)}
          className="px-0 text-base hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0"
        >
          {minimized ? (
            <Expand className="size-6" />
          ) : (
            <Minimize2 className="size-6" />
          )}
          <span className="sr-only">Toggle Menu</span>
        </Button>
      </div>
      <div className={cn("px-4 text-lg", minimized && "px-0")}>
        <ARMinimizableLinks
          isAdmin={isAdmin}
          setOpen={toggleSidebar}
          pathname={pathname}
          minimized={minimized}
        />
      </div>
    </motion.nav>
  );
};
