'use client'

import * as React from 'react'
import { Button } from '@admin/components/ui/button'
import { Textarea } from '@admin/components/ui/textarea'
import { TrashIcon } from 'lucide-react'

export interface MathEditorControlsProps {
  disabled?: boolean
  initialValue?: string
  onApply: (value: string) => boolean | undefined
  onComplete?: () => void
  onRemove?: () => boolean | undefined
}

export function MathEditorControls({
  disabled,
  initialValue = '',
  onApply,
  onComplete,
  onRemove
}: MathEditorControlsProps) {
  const [value, setValue] = React.useState(initialValue)
  const textareaRef = React.useRef<HTMLTextAreaElement>(null)
  const canApply = Boolean(value.trim()) && !disabled

  React.useEffect(() => {
    if (disabled) return

    textareaRef.current?.focus({ preventScroll: true })
  }, [disabled])

  const applyMath = React.useCallback(() => {
    if (!canApply) return

    const didApply = onApply(value)
    if (didApply === false) return

    if (!initialValue) {
      setValue('')
    }
    onComplete?.()
  }, [canApply, initialValue, onApply, onComplete, value])

  const removeMath = React.useCallback(() => {
    if (disabled || !onRemove) return

    const didRemove = onRemove()
    if (didRemove === false) return

    onComplete?.()
  }, [disabled, onComplete, onRemove])

  const handleKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
      if (event.key !== 'Enter' || (!event.metaKey && !event.ctrlKey)) return

      event.preventDefault()
      applyMath()
    },
    [applyMath]
  )

  return (
    <div className="flex w-72 flex-col gap-3 p-4">
      <Textarea
        ref={textareaRef}
        value={value}
        onChange={(event) => setValue(event.target.value)}
        onKeyDown={handleKeyDown}
        placeholder="Paste LaTeX..."
        disabled={disabled}
        className="min-h-24 resize-y rounded-md text-sm"
      />

      <div className="flex flex-wrap items-center gap-1">
        {onRemove ? (
          <Button
            type="button"
            variant="destructive"
            disabled={disabled}
            aria-label="Remove math"
            title="Remove"
            onClick={removeMath}
          >
            <TrashIcon />
          </Button>
        ) : null}

        <Button
          type="button"
          variant="default"
          className="flex-1"
          disabled={!canApply}
          aria-label="Enter math"
          title="Enter"
          onClick={applyMath}
        >
          Insert
        </Button>
      </div>
    </div>
  )
}
