import type { ComponentType } from 'react'
import { Loader2, MoreHorizontal } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

export type AdminRowAction = {
  label: string
  icon?: ComponentType<{ className?: string }>
  onSelect?: () => void
  disabled?: boolean
  destructive?: boolean
  separatorBefore?: boolean
}

type AdminRowActionsMenuProps = {
  label: string
  actions: AdminRowAction[]
  loading?: boolean
  align?: 'start' | 'center' | 'end'
}

export function AdminRowActionsMenu({
  label,
  actions,
  loading = false,
  align = 'end',
}: AdminRowActionsMenuProps) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant='ghost'
          className='h-8 w-8 p-0 data-[state=open]:bg-muted'
          disabled={loading}
        >
          <span className='sr-only'>{label}</span>
          {loading ? (
            <Loader2 className='size-4 animate-spin' />
          ) : (
            <MoreHorizontal className='size-4' />
          )}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align={align} className='admin-menu-content'>
        <DropdownMenuLabel>{label}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {actions.map((action, index) => {
          const Icon = action.icon
          return (
            <div key={`${action.label}-${index}`}>
              {action.separatorBefore ? <DropdownMenuSeparator /> : null}
              <DropdownMenuItem
                disabled={action.disabled}
                variant={action.destructive ? 'destructive' : 'default'}
                onSelect={action.onSelect}
              >
                {Icon ? <Icon className='size-4' /> : null}
                {action.label}
              </DropdownMenuItem>
            </div>
          )
        })}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
