"use client";

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

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

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

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type DataTableRowActionsProps<TData, TValue = unknown> = {
  className?: string;
  actions?: DataTablaRowActionFunction<TData>;
  rowContext: CellContext<TData, unknown>;
};

export function DataTableRowActions<TData = any, TValue = unknown>({
  actions,
  rowContext,
  className,
}: DataTableRowActionsProps<TData, TValue>) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          aria-haspopup='true'
          size='icon'
          variant='link'
          className={cn("w-4 h-4 mt-2 text-ring hover:text-muted-foreground", className)}
        >
          <MoreHorizontalIcon className='w-4 h-4' />
          <span className='sr-only'>{t("common.open_menu")}</span>
        </Button>
      </DropdownMenuTrigger>

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