'use client'

import type { ControlAvailability, ControlShortcut, ControlTooltip } from '../control-options'
import type { UseUndoRedoConfig } from '@admin/hooks/content-editor/use-undo-redo'
import type { BaseUIEvent } from '@base-ui/react'
import { Button } from '@admin/components/ui/button'
import { useTiptapEditor } from '@admin/hooks/content-editor/use-tiptap-editor'
import { useUndoRedo } from '@admin/hooks/content-editor/use-undo-redo'
import { useCallback } from 'react'
import {
  getControlTooltipTitle,
  shouldHideUnavailableControl,
  shouldShowControlShortcut
} from '../control-options'
import { HistoryShortcutBadge } from './history-shortcut-badge'

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

export { HistoryShortcutBadge } from './history-shortcut-badge'

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

export function UndoRedoButton({
  editor: providedEditor,
  action,
  availability,
  text,
  onExecuted,
  shortcut,
  tooltip,
  onClick,
  children,
  ref,
  ...buttonProps
}: UndoRedoButtonProps) {
  const { editor } = useTiptapEditor(providedEditor)
  const { isVisible, handleAction, label, canExecute, Icon, shortcutKeys } = useUndoRedo({
    editor,
    action,
    hideWhenUnavailable: shouldHideUnavailableControl(availability),
    onExecuted
  })

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

  if (!isVisible) {
    return null
  }

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