'use client'

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

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

export { MarkShortcutBadge } from './mark-shortcut-badge'

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

export function MarkButton({
  editor: providedEditor,
  availability,
  type,
  text,
  onToggled,
  shortcut,
  tooltip,
  onClick,
  children,
  ref,
  ...buttonProps
}: MarkButtonProps) {
  const { editor } = useTiptapEditor(providedEditor)
  const { isVisible, handleMark, label, canToggle, isActive, Icon, shortcutKeys } = useMark({
    editor,
    type,
    hideWhenUnavailable: shouldHideUnavailableControl(availability),
    onToggled
  })

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

  if (!isVisible) {
    return null
  }

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