// ── Notes: Note Form Component ──
// Input form to add a new note to a lead. Shows the current user's avatar,
// a textarea for the note, and a submit button. Enter key submits (Shift+Enter for newline).

"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Send } from "lucide-react"
import { useUser } from "@/providers/user-provider"

interface NoteFormProps {
  leadId: string
  onNoteAdded?: () => void
}

/**
 * NoteForm — compact form to create a new note on a lead.
 * Posts to /api/leads/{leadId}/notes and calls onNoteAdded on success.
 */
export function NoteForm({ leadId, onNoteAdded }: NoteFormProps) {
  const { user } = useUser()
  const [note, setNote] = useState("")
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async () => {
    if (!note.trim()) return
    setSubmitting(true)
    try {
      await fetch(`/api/leads/${leadId}/notes`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content: note }),
      })
      setNote("")
      onNoteAdded?.()
    } catch {
      console.warn("Failed to add note")
    }
    setSubmitting(false)
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSubmit()
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Add Note</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }}>
          <div className="flex gap-4">
            <Avatar className="h-10 w-10 shrink-0">
              <AvatarImage src={user?.avatar || undefined} />
              <AvatarFallback>{user?.name?.charAt(0) || "U"}</AvatarFallback>
            </Avatar>
            <div className="flex-1 space-y-3">
              <Textarea
                placeholder="Write a note about this lead..."
                value={note}
                onChange={(e) => setNote(e.target.value)}
                onKeyDown={handleKeyDown}
                className="min-h-[100px] resize-none"
              />
              <div className="flex justify-end">
                <Button
                  type="submit"
                  disabled={!note.trim() || submitting}
                  className="gap-2"
                >
                  <Send className="h-4 w-4" />
                  {submitting ? "Adding..." : "Add Note"}
                </Button>
              </div>
            </div>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
