"use client";

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

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

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

export type DataTableRowActionsProps<TData, _TValue = unknown> = {
  className?: string;
  actions?: DataTablaRowActionFunction<TData>;
  rowContext: CellContext<TData, unknown>;
};

export function DataTableRowActions<TData = any, TValue = unknown>({
  actions,
  rowContext,
}: DataTableRowActionsProps<TData, TValue>) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button size='icon' variant='outline' className='w-8 h-8'>
          <MoreVerticalIcon className='h-3.5 w-3.5' />
          <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.icon && <>{action.icon}</>}
                {action.label}
                {action.shortcut && <DropdownMenuShortcut>{action.shortcut}</DropdownMenuShortcut>}
              </DropdownMenuItem>
            )
          )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
