"use client";

import { usePathname, useRouter } from "next/navigation";
import { useTransition } from "react";
import { cn } from "@/lib/utils";

export function SettingsSidebarLink({
  href,
  icon,
  children,
}: {
  href: string;
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const isActive = pathname === href;
  const [isPending, startTransition] = useTransition();

  function handleClick(e: React.MouseEvent) {
    e.preventDefault();
    if (isActive) return;
    startTransition(() => router.push(href));
  }

  return (
    <button
      onClick={handleClick}
      disabled={isPending}
      className={cn(
        "w-full flex items-center gap-2.5 px-3 py-1.5 rounded-md text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed",
        isActive
          ? "bg-gray-200/70 text-gray-900 font-medium"
          : "text-gray-600 font-normal hover:bg-gray-100 hover:text-gray-900"
      )}
    >
      <span
        className={cn(
          "shrink-0",
          isActive ? "text-gray-700" : "text-gray-400"
        )}
      >
        {isPending ? (
          <span className="animate-spin h-4 w-4 border-2 border-gray-400 border-t-transparent rounded-full block" />
        ) : (
          icon
        )}
      </span>
      {children}
    </button>
  );
}
