"use client";

import { useRouter } from "next/navigation";

import { TableCell, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";

interface ClickableTableRowProps {
  href: string;
  children: React.ReactNode;
  className?: string;
}

export function ClickableTableRow({ href, children, className }: ClickableTableRowProps) {
  const router = useRouter();

  const navigate = () => router.push(href);

  return (
    <TableRow
      tabIndex={0}
      role="link"
      aria-label="Open row"
      className={cn("cursor-pointer hover:bg-muted/50 focus-visible:bg-muted/50 focus-visible:outline-none", className)}
      onClick={(e) => {
        const target = e.target as HTMLElement;
        if (target.closest("[data-no-row-nav]")) return;
        navigate();
      }}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          navigate();
        }
      }}
    >
      {children}
    </TableRow>
  );
}

export function RowActionsCell({ children, className }: { children: React.ReactNode; className?: string }) {
  return (
    <TableCell
      data-no-row-nav
      className={cn("text-right", className)}
      onClick={(e) => e.stopPropagation()}
      onKeyDown={(e) => e.stopPropagation()}
    >
      {children}
    </TableCell>
  );
}
