'use client'

import * as React from 'react'
import { Button } from '@admin/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuTrigger
} from '@admin/components/ui/dropdown-menu'
import { ChevronDownIcon } from 'lucide-react'

type SvgIcon = React.ComponentType<{ className?: string }>

export interface SourceModeDropdownButtonProps {
  label: string
  ariaLabel?: string
  Icon: SvgIcon
  children: React.ReactNode
}

export function SourceModeDropdownButton({
  label,
  ariaLabel,
  Icon,
  children
}: SourceModeDropdownButtonProps) {
  const [isOpen, setIsOpen] = React.useState(false)

  return (
    <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
      <DropdownMenuTrigger
        render={
          <Button
            type="button"
            variant="ghost"
            size="icon-sm"
            className="w-auto px-2"
            aria-label={ariaLabel ?? label}
            title={label}
            onPointerDown={(event) => event.preventDefault()}
            onClick={() => setIsOpen((current) => !current)}
          />
        }
      >
        <Icon />
        <ChevronDownIcon className="tiptap-button-dropdown-small" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-auto min-w-40">
        <DropdownMenuGroup>{children}</DropdownMenuGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
