'use client'

import * as React from 'react'
import type { MathButtonProps } from './math-button'
import type { Editor } from '@tiptap/core'
import { Popover, PopoverContent, PopoverTrigger } from '@admin/components/ui/popover'
import { useTiptapEditor } from '@admin/hooks/content-editor/use-tiptap-editor'
import { insertContentEditorMath } from '@admin/utils/editor/insert-content-editor-math'
import { MathButton } from './math-button'
import { MathEditorControls } from './math-editor-controls'

export interface MathPopoverButtonProps extends Omit<MathButtonProps, 'onClick'> {
  editor?: Editor | null
  onInsertMath?: (value: string) => boolean | undefined
}

export function MathPopoverButton({
  disabled,
  editor: providedEditor,
  onInsertMath,
  text = 'Math',
  ...buttonProps
}: MathPopoverButtonProps) {
  const { editor } = useTiptapEditor(providedEditor)
  const [isOpen, setIsOpen] = React.useState(false)
  const canInsert = Boolean(onInsertMath || editor?.isEditable)

  const applyMath = React.useCallback(
    (value: string) => {
      if (disabled || !canInsert) return false

      return onInsertMath ? onInsertMath(value) : insertContentEditorMath(editor, value)
    },
    [canInsert, disabled, editor, onInsertMath]
  )

  return (
    <Popover open={isOpen} onOpenChange={setIsOpen}>
      <PopoverTrigger
        render={
          <MathButton
            {...buttonProps}
            text={text}
            disabled={disabled || !canInsert}
            aria-label="Insert math"
            title="Math"
            onPointerDown={(event) => event.preventDefault()}
            onClick={() => setIsOpen((current) => !current)}
          />
        }
      />
      <PopoverContent align="start" className="w-auto gap-0 p-0">
        <MathEditorControls
          disabled={disabled || !canInsert}
          onApply={applyMath}
          onComplete={() => setIsOpen(false)}
        />
      </PopoverContent>
    </Popover>
  )
}
