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

interface Props {
  text: string
  onSave: (next: string) => Promise<void>
  className?: string
}

// Inline-editable comment text. Click to enter edit mode (handled by parent),
// or pass `editing` to control externally. This component focuses on the
// editing interaction itself with a clean save/cancel UX.
export function EditableComment({ text, onSave, className = '' }: Props) {
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState(text)
  const [busy, setBusy] = useState(false)
  const ref = useRef<HTMLTextAreaElement>(null)

  useEffect(() => { setDraft(text) }, [text])

  useEffect(() => {
    if (editing && ref.current) {
      ref.current.focus()
      // Place cursor at end
      ref.current.setSelectionRange(ref.current.value.length, ref.current.value.length)
    }
  }, [editing])

  async function save() {
    if (busy) return
    if (!draft.trim()) return
    if (draft === text) { setEditing(false); return }
    setBusy(true)
    try {
      await onSave(draft.trim())
      setEditing(false)
    } finally {
      setBusy(false)
    }
  }

  function cancel() {
    setDraft(text)
    setEditing(false)
  }

  if (editing) {
    return (
      <div onClick={(e) => e.stopPropagation()}>
        <textarea
          ref={ref}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); save() }
            if (e.key === 'Escape') { e.preventDefault(); cancel() }
          }}
          rows={Math.max(2, Math.min(8, draft.split('\n').length + 1))}
          className="w-full px-2.5 py-1.5 rounded border border-blue-300 dark:border-blue-800 bg-blue-50/40 dark:bg-blue-950/30 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-200 dark:focus:ring-blue-900 resize-y leading-relaxed"
        />
        <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 save · esc to cancel</span>
          <button
            onClick={cancel}
            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={save}
            disabled={busy || !draft.trim() || draft === text}
            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 ? 'saving…' : 'save'}
          </button>
        </div>
      </div>
    )
  }

  return (
    <div
      onClick={(e) => { e.stopPropagation(); setEditing(true) }}
      title="Click to edit"
      className={`cursor-text rounded -mx-1 px-1 transition-colors hover:bg-blue-50/60 dark:hover:bg-blue-950/30 ${className}`}
    >
      {text}
    </div>
  )
}
