"use client";

import {
  Button,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuTrigger,
} from "@/ui";
import { CellContext } from "@tanstack/react-table";
import { MoreHorizontalIcon } from "lucide-react";

type DataTableRowActionContext<TData, TValue> = CellContext<TData, TValue>;

export type DataTablaRowActionFunction<TData, TValue> = (
  props: DataTableRowActionContext<TData, TValue>,
) => DataTableRowActionDefinition<TData, TValue>[];

export type DataTableRowActionDefinition<TData, TValue> = {
  label: string | "-";
  shortcut?: string;
  onClick?: (
    props: DataTableRowActionContext<TData, TValue>,
    e: React.BaseSyntheticEvent,
  ) => void;
};

export type DataTableRowActionsProps<TData, TValue> = {
  props: DataTableRowActionContext<TData, TValue>;
  actions?: DataTablaRowActionFunction<TData, TValue>;
};

export function DataTableRowActions<TData, TValue>({
  actions,
  ...props
}: DataTableRowActionsProps<TData, TValue>) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          aria-haspopup="true"
          size="icon"
          variant="link"
          className="w-4 h-4 translate-y-[2px]"
        >
          <MoreHorizontalIcon className="w-4 h-4" />
          <span className="sr-only">Abrir menú</span>
        </Button>
      </DropdownMenuTrigger>

      <DropdownMenuContent align="end">
        <DropdownMenuLabel>Acciones</DropdownMenuLabel>
        {actions &&
          actions(props).map((action, index) =>
            action.label === "-" ? (
              <DropdownMenuSeparator key={index} />
            ) : (
              <DropdownMenuItem
                key={index}
                onClick={(event) =>
                  action.onClick ? action.onClick(props, event) : null
                }
              >
                {action.label}
                <DropdownMenuShortcut>{action.shortcut}</DropdownMenuShortcut>
              </DropdownMenuItem>
            ),
          )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
