import { useEffect, useRef, useState } from 'react'

interface Props {
  onSubmit: (text: string) => Promise<void> | void
  onCancel?: () => void
  placeholder?: string
  buttonLabel?: string
  autoFocus?: boolean
  compact?: boolean
}

export function InlineCommentBox({
  onSubmit,
  onCancel,
  placeholder = 'Add your comment or question…',
  buttonLabel = 'post',
  autoFocus = true,
  compact = false,
}: Props) {
  const [text, setText] = useState('')
  const [busy, setBusy] = useState(false)
  const ref = useRef<HTMLTextAreaElement>(null)

  useEffect(() => {
    if (autoFocus && ref.current) ref.current.focus()
  }, [autoFocus])

  async function submit() {
    if (!text.trim() || busy) return
    setBusy(true)
    try {
      await onSubmit(text.trim())
      setText('')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className={compact ? 'mt-1.5' : 'mt-2'}>
      <div className="flex items-baseline gap-1.5 mb-1">
        <span className="font-mono text-[9px] uppercase tracking-[0.12em] font-semibold text-blue-600 dark:text-blue-400">
          &gt; director [joe]:
        </span>
      </div>
      <textarea
        ref={ref}
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
            e.preventDefault()
            submit()
          }
          if (e.key === 'Escape' && onCancel) {
            e.preventDefault()
            onCancel()
          }
        }}
        placeholder={placeholder}
        rows={compact ? 2 : 3}
        className="w-full px-2.5 py-1.5 rounded border border-blue-200 dark:border-blue-900 bg-blue-50/30 dark:bg-blue-950/20 text-sm text-gray-900 dark:text-gray-100 placeholder:text-gray-400 dark:placeholder:text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-900 resize-y"
      />
      <div className="flex items-center justify-end gap-2 mt-1.5">
        <span className="font-mono text-[9px] text-gray-400 mr-auto">cmd+enter to post · esc to cancel</span>
        {onCancel && (
          <button
            onClick={onCancel}
            disabled={busy}
            className="px-2.5 py-1 rounded text-[10px] font-mono uppercase tracking-wider text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 cursor-pointer"
          >
            cancel
          </button>
        )}
        <button
          onClick={submit}
          disabled={busy || !text.trim()}
          className="px-3 py-1 rounded text-[10px] font-mono uppercase tracking-wider bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50 cursor-pointer"
        >
          {busy ? 'posting…' : buttonLabel}
        </button>
      </div>
    </div>
  )
}
