'use client'

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

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

export { CodeBlockShortcutBadge } from './code-block-shortcut-badge'

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

export function CodeBlockButton({
  editor: providedEditor,
  availability,
  text,
  onToggled,
  shortcut,
  tooltip,
  onClick,
  children,
  ref,
  ...buttonProps
}: CodeBlockButtonProps) {
  const { editor } = useTiptapEditor(providedEditor)
  const { isVisible, canToggle, isActive, handleToggle, label, shortcutKeys, Icon } = useCodeBlock({
    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"
      disabled={!canToggle}
      data-disabled={!canToggle}
      tabIndex={-1}
      aria-label={label}
      aria-pressed={isActive}
      title={getControlTooltipTitle(tooltip, 'Code Block')}
      onClick={handleClick}
      {...buttonProps}
      ref={ref}
    >
      {children ?? (
        <>
          <Icon />
          {text && <span className="tiptap-button-text">{text}</span>}
          {shouldShowControlShortcut(shortcut) && (
            <CodeBlockShortcutBadge shortcutKeys={shortcutKeys} />
          )}
        </>
      )}
    </Button>
  )
}
