import Link from "next/link";
import { ArrowDown, ArrowUp, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/cn";
import { dashboardHref, type DashboardQuery, type SortKey } from "@/lib/dashboard-query";

type SortableHeaderProps = {
  label: string;
  sortKey: SortKey;
  query: DashboardQuery;
  align?: "left" | "right";
};

export function SortableHeader({ label, sortKey, query, align = "left" }: SortableHeaderProps) {
  const active = query.sort === sortKey;
  const nextDir = active && query.dir === "asc" ? "desc" : "asc";
  const Icon = !active ? ChevronsUpDown : query.dir === "asc" ? ArrowUp : ArrowDown;

  return (
    <th
      scope="col"
      aria-sort={active ? (query.dir === "asc" ? "ascending" : "descending") : undefined}
      className={cn("px-4 py-2.5 text-xs font-medium", align === "right" ? "text-right" : "text-left")}
    >
      <Link
        href={dashboardHref(query, { sort: sortKey, dir: nextDir, page: 1 })}
        className={cn(
          "inline-flex items-center gap-1 rounded-sm hover:text-slate-900",
          align === "right" && "flex-row-reverse",
          active ? "text-slate-900" : "text-slate-500",
        )}
      >
        {label}
        <Icon className={cn("size-3", !active && "text-slate-400")} aria-hidden />
      </Link>
    </th>
  );
}
