import Link from "next/link";

type Props = {
  /** Trenutna vrednost sort param-a iz URL-a. */
  current?: string;
  /** Vrednost koju ovaj link šalje (ako klikneš na njega — postaje aktivan). */
  value: string;
  /** Vidljivi label u header-u tabele. */
  label: string;
  /** Search params koji se preserve-uju (sve osim `sort` i `page`). */
  preserve: Record<string, string | undefined>;
  /** Base path stranice. */
  basePath: string;
  /** Da li je ovaj sort default? (Ne klikabilno kad je već default i nema druge opcije.) */
};

/**
 * Klikabilni table header koji menja `?sort=` param. Koristi se u svakoj
 * admin tabeli — ekstrahovano da ne kopiramo `URLSearchParams` logiku.
 */
export function SortLink({ current, value, label, preserve, basePath }: Props) {
  const isActive = current === value;

  const params = new URLSearchParams();
  for (const [k, v] of Object.entries(preserve)) {
    if (k === "sort" || k === "page") continue;
    if (typeof v === "string" && v.length > 0) params.set(k, v);
  }
  params.set("sort", value);
  const href = `${basePath}?${params.toString()}`;

  return (
    <Link
      href={href}
      prefetch={false}
      aria-current={isActive ? "true" : undefined}
      className={`inline-flex items-center gap-1 transition ${
        isActive ? "text-primary" : "text-muted-foreground hover:text-foreground"
      }`}
    >
      {label}
      {isActive && (
        <svg
          width="11"
          height="11"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M6 9l6 6 6-6" />
        </svg>
      )}
    </Link>
  );
}
