"use client";

import Link from "next/link";
import { MoreHorizontalIcon, type LucideIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuLinkItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export type RowAction = {
  label: string;
  icon?: LucideIcon;
  /** Navigates: rendered as a real link. */
  href?: string;
  /** Acts in place (opens a dialog, prints): rendered as a menu item. Used when there is no href. */
  onSelect?: () => void;
  /** Destructive actions are grouped last, after a separator, in red. */
  destructive?: boolean;
};

/**
 * The one way to show row actions in a Medora table: a ghost "more" (horizontal ellipsis) button that opens
 * a menu. Links come first, destructive actions last. `label` names the row for the menu heading and the
 * button's accessible name ("Actions for Panadol 500 mg").
 */
export function RowActions({ label, actions, className }: { label: string; actions: RowAction[]; className?: string }) {
  // Nothing the role may do on this row: no button, rather than a menu that opens empty.
  if (!actions.length) return null;
  const safe = actions.filter((a) => !a.destructive);
  const danger = actions.filter((a) => a.destructive);

  const item = (a: RowAction) => {
    const content = (
      <>
        {a.icon ? <a.icon /> : null}
        {a.label}
      </>
    );
    const variant = a.destructive ? "destructive" : "default";
    return a.href ? (
      <DropdownMenuLinkItem key={a.label} variant={variant} render={<Link href={a.href} />}>
        {content}
      </DropdownMenuLinkItem>
    ) : (
      <DropdownMenuItem key={a.label} variant={variant} onClick={a.onSelect}>
        {content}
      </DropdownMenuItem>
    );
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger render={<Button variant="ghost" size="icon-sm" aria-label={`Actions for ${label}`} className={className} />}>
        <MoreHorizontalIcon />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-52">
        {/* The label is Base UI's GroupLabel, which must sit inside a group. */}
        <DropdownMenuGroup>
          <DropdownMenuLabel className="truncate">{label}</DropdownMenuLabel>
          {safe.map(item)}
        </DropdownMenuGroup>
        {danger.length ? (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuGroup>{danger.map(item)}</DropdownMenuGroup>
          </>
        ) : null}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
