/**
 * "+ Add a note" affordance for the What-we-know section.
 *
 * Inline composer that posts a `user_note` fact when the engineer wants to
 * record something the AI didn't surface (a hunch, an observation, a piece
 * of customer context). Per FLOWPILOT-MIGRATION.md Section 3.1.
 */
import { useState } from 'react'
import { Plus, Check } from 'lucide-react'

interface AddNoteButtonProps {
  onAdd: (text: string, summary: string | null) => Promise<void> | void
}

export function AddNoteButton({ onAdd }: AddNoteButtonProps) {
  const [open, setOpen] = useState(false)
  const [text, setText] = useState('')
  const [summary, setSummary] = useState('')
  const [busy, setBusy] = useState(false)

  const reset = () => {
    setText('')
    setSummary('')
    setOpen(false)
  }

  const handleSubmit = async () => {
    if (!text.trim()) return
    setBusy(true)
    try {
      await onAdd(text.trim(), summary.trim() || null)
      reset()
    } finally {
      setBusy(false)
    }
  }

  if (!open) {
    return (
      <button
        onClick={() => setOpen(true)}
        className="flex items-center gap-1.5 text-[0.75rem] text-muted-foreground hover:text-accent-text transition-colors pl-1 mt-1"
      >
        <Plus size={12} />
        Add a note
      </button>
    )
  }

  return (
    <div className="rounded-lg border border-default bg-card p-3 mb-2">
      <textarea
        autoFocus
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="What did you observe or confirm?"
        className="w-full rounded-md border border-default bg-input px-2.5 py-1.5 text-[0.8125rem] text-heading placeholder:text-muted-foreground resize-y min-h-[44px] max-h-[140px] focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30"
        rows={2}
      />
      <input
        type="text"
        value={summary}
        onChange={(e) => setSummary(e.target.value)}
        placeholder="Short label (optional)"
        className="mt-1.5 w-full rounded-md border border-default bg-input px-2.5 py-1 text-[0.75rem] text-heading placeholder:text-muted-foreground focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/30"
      />
      <div className="mt-1.5 flex items-center gap-2">
        <button
          onClick={handleSubmit}
          disabled={busy || !text.trim()}
          className="flex items-center gap-1 rounded-md bg-accent px-2.5 py-1 text-[0.75rem] font-medium text-white disabled:opacity-40 hover:bg-accent-hover transition-colors"
        >
          <Check size={11} /> Add
        </button>
        <button
          onClick={reset}
          disabled={busy}
          className="text-[0.75rem] text-muted-foreground hover:text-heading"
        >
          Cancel
        </button>
      </div>
    </div>
  )
}

export default AddNoteButton
