'use client'

import type { ControlAvailability, ControlShortcut, ControlTooltip } from '../control-options'
import type { UseBlockquoteConfig } from '@admin/hooks/content-editor/use-blockquote'
import type { BaseUIEvent } from '@base-ui/react'
import { Button } from '@admin/components/ui/button'
import { useBlockquote } from '@admin/hooks/content-editor/use-blockquote'
import { useTiptapEditor } from '@admin/hooks/content-editor/use-tiptap-editor'
import { useCallback } from 'react'
import {
  getControlTooltipTitle,
  shouldHideUnavailableControl,
  shouldShowControlShortcut
} from '../control-options'
import { BlockquoteShortcutBadge } from './blockquote-shortcut-badge'

type EditorButtonProps = React.ComponentProps<typeof Button> & {
  tooltip?: ControlTooltip
}

export { BlockquoteShortcutBadge } from './blockquote-shortcut-badge'

export interface BlockquoteButtonProps
  extends Omit<EditorButtonProps, 'type'>, Omit<UseBlockquoteConfig, 'hideWhenUnavailable'> {
  availability?: ControlAvailability
  text?: string
  shortcut?: ControlShortcut
}

export function BlockquoteButton({
  editor: providedEditor,
  availability,
  text,
  onToggled,
  shortcut,
  tooltip,
  onClick,
  children,
  ref,
  ...buttonProps
}: BlockquoteButtonProps) {
  const { editor } = useTiptapEditor(providedEditor)
  const { isVisible, canToggle, isActive, handleToggle, label, shortcutKeys, Icon } = useBlockquote(
    {
      editor,
      hideWhenUnavailable: shouldHideUnavailableControl(availability),
      onToggled
    }
  )

  const handleClick = useCallback(
    (event: BaseUIEvent<React.MouseEvent<HTMLButtonElement>>) => {
      onClick?.(event)
      if (event.defaultPrevented) return
      handleToggle()
    },
    [handleToggle, onClick]
  )

  if (!isVisible) {
    return null
  }

  return (
    <Button
      type="button"
      variant="ghost"
      size={text ? 'sm' : 'icon-sm'}
      data-active-state={isActive ? 'on' : 'off'}
      role="button"
      tabIndex={-1}
      disabled={!canToggle}
      data-disabled={!canToggle}
      aria-label={label}
      aria-pressed={isActive}
      title={getControlTooltipTitle(tooltip, 'Blockquote')}
      onClick={handleClick}
      {...buttonProps}
      ref={ref}
    >
      {children ?? (
        <>
          <Icon />
          {text && <span className="tiptap-button-text">{text}</span>}
          {shouldShowControlShortcut(shortcut) && (
            <BlockquoteShortcutBadge shortcutKeys={shortcutKeys} />
          )}
        </>
      )}
    </Button>
  )
}
