import { Button, DropdownMenu, SvgUse } from "@ivtui/base"
import clsx from "clsx"
import type { JSX } from "react"
import { useCallback, useState } from "react"
import type { DataTableRowItemAction } from "../DataTable.types"

interface RowActionsCellProps<TData> {
  row: any
  actions: DataTableRowItemAction<TData>[]
}

export function RowActionsCell<TData>({
  row,
  actions,
}: Readonly<RowActionsCellProps<TData>>): JSX.Element {
  const [open, setOpen] = useState(false)

  const handleActionClick = useCallback(
    (action: DataTableRowItemAction<TData>) => {
      action.onClick(row.original)
      setOpen(false)
    },
    [row.original],
  )

  return (
    <DropdownMenu.Root open={open} onOpenChange={setOpen}>
      <DropdownMenu.Trigger>
        <Button
          variant="outline"
          className="!p-1 !shadow-none"
          color="gray"
          highContrast
          onClick={e => e.stopPropagation()}
        >
          <SvgUse icon="dots-vertical" className="size-4" />
        </Button>
      </DropdownMenu.Trigger>
      <DropdownMenu.Content align="end" className="w-fit" color="indigo">
        {actions.map((action, index) => (
          <DropdownMenu.Item
            key={`${action.label}-${index}`}
            onClick={() => handleActionClick(action)}
            disabled={action.disabled}
            className={clsx(
              "cursor-pointer",
              action.variant === "destructive" && "text-destructive focus:text-destructive",
            )}
          >
            {action.icon &&
              (typeof action.icon === "string" ? (
                <SvgUse icon={action.icon} className="size-4" />
              ) : (
                <span className="size-4 flex items-center justify-center">{action.icon}</span>
              ))}
            {action.label}
          </DropdownMenu.Item>
        ))}
      </DropdownMenu.Content>
    </DropdownMenu.Root>
  )
}
