import { cn } from "@/lib/utils";
import { cva } from "class-variance-authority";
import Link from "next/link";
import { useSidebarContext } from "./sidebar-context";

const menuItemBaseStyles = cva(
  "rounded-xl border border-transparent px-3.5 font-semibold text-dark-4 shadow-[inset_0_0_0_1px_transparent] transition-all duration-200 dark:text-dark-6",
  {
    variants: {
      isActive: {
        true: "border-primary/20 bg-gradient-to-r from-primary/[0.14] to-primary/[0.05] text-primary shadow-theme-xs hover:from-primary/[0.16] hover:to-primary/[0.08] dark:border-primary/30 dark:from-primary/[0.28] dark:to-primary/[0.12] dark:text-white",
        false:
          "hover:-translate-y-0.5 hover:border-stroke/80 hover:bg-white/80 hover:text-dark hover:shadow-theme-xs dark:hover:border-dark-3 dark:hover:bg-white/[0.08] dark:hover:text-white",
      },
      isCollapsed: {
        true: "justify-center px-2",
        false: "",
      },
    },
    defaultVariants: {
      isActive: false,
      isCollapsed: false,
    },
  },
);

export function MenuItem(
  props: {
    className?: string;
    children: React.ReactNode;
    isActive: boolean;
    isCollapsed?: boolean;
    title?: string;
  } & ({ as?: "button"; onClick: () => void } | { as: "link"; href: string }),
) {
  const { toggleSidebar, isMobile, isOpen } = useSidebarContext();

  if (props.as === "link") {
    return (
      <Link
        href={props.href}
        // Close sidebar on clicking link if it's mobile and expanded
        onClick={() => isMobile && isOpen && toggleSidebar()}
        className={cn(
          menuItemBaseStyles({
            isActive: props.isActive,
            isCollapsed: props.isCollapsed,
            className: "relative block py-2.5",
          }),
          props.className,
        )}
        title={props.isCollapsed ? props.title : undefined}
      >
        {props.children}
      </Link>
    );
  }

  return (
    <button
      onClick={props.onClick}
      aria-expanded={props.isActive}
      className={menuItemBaseStyles({
        isActive: props.isActive,
        isCollapsed: props.isCollapsed,
        className: cn(
          "flex w-full items-center gap-3 py-3",
          props.isCollapsed && "justify-center",
        ),
      })}
      title={props.isCollapsed ? props.title : undefined}
    >
      {props.children}
    </button>
  );
}
