"use client"

import { useState } from "react"

interface HighlightSelectionToolbarProperties {
  selectionRect: DOMRect
  containerRect: DOMRect
  onHighlight: (note: string | null) => void
  onDismiss: () => void
}

export function HighlightSelectionToolbar({
  selectionRect,
  onHighlight,
  onDismiss,
}: HighlightSelectionToolbarProperties) {
  const [showNoteInput, setShowNoteInput] = useState(false)
  const [noteText, setNoteText] = useState("")

  const toolbarLeft = selectionRect.left + selectionRect.width / 2
  const toolbarTop = selectionRect.top - 8

  function handleHighlightClick() {
    if (showNoteInput) {
      onHighlight(noteText.trim() || null)
    } else {
      onHighlight(null)
    }
  }

  return (
    <div
      className="fixed z-[100] -translate-x-1/2 -translate-y-full"
      style={{ left: toolbarLeft, top: toolbarTop }}
    >
      <div className="border border-border bg-background-secondary p-1">
        {showNoteInput ? (
          <div className="flex items-center gap-1">
            <input
              type="text"
              value={noteText}
              onChange={(event) => setNoteText(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Enter") handleHighlightClick()
                if (event.key === "Escape") onDismiss()
              }}
              placeholder="add a note..."
              className="border border-border bg-background-primary px-2 py-1 text-xs text-text-primary outline-none"
              autoFocus
            />
            <button
              type="button"
              onClick={handleHighlightClick}
              className="px-2 py-1 text-xs text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
            >
              save
            </button>
          </div>
        ) : (
          <div className="flex items-center gap-1">
            <button
              type="button"
              onClick={handleHighlightClick}
              className="px-2 py-1 text-xs text-text-secondary transition-colors hover:bg-background-tertiary hover:text-text-primary"
            >
              highlight
            </button>
            <button
              type="button"
              onClick={() => setShowNoteInput(true)}
              className="px-2 py-1 text-xs text-text-dim transition-colors hover:bg-background-tertiary hover:text-text-secondary"
            >
              + note
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
