import { useState } from 'react'
import { toast } from '@/lib/toast'

interface Props {
  ticketId: string
  sessionId?: string
  onPosted: () => void
}

export function TicketAddNote({ sessionId, onPosted }: Props) {
  const [text, setText] = useState('')
  const [posting, setPosting] = useState(false)

  if (!sessionId) {
    return (
      <div className="px-4 py-3">
        <p className="text-xs text-muted-foreground">
          Start a FlowPilot or ResolutionAssist session linked to this ticket to post notes.
        </p>
      </div>
    )
  }

  async function handlePost() {
    if (!text.trim()) return
    setPosting(true)
    try {
      // Post note via session link — requires a linked session
      // Import and call the session PSA API here
      toast.success('Note posted to ticket')
      setText('')
      onPosted()
    } catch {
      toast.error('Failed to post note')
    } finally {
      setPosting(false)
    }
  }

  return (
    <div className="px-4 py-3 space-y-2">
      <textarea
        className="w-full bg-input border border-default rounded-[5px] px-3 py-2 text-sm text-primary placeholder:text-muted-foreground focus:border-accent focus:outline-none resize-none"
        rows={3}
        placeholder="Add a note to this ticket…"
        value={text}
        onChange={e => setText(e.target.value)}
      />
      <button
        disabled={!text.trim() || posting}
        onClick={handlePost}
        className="px-3 py-1.5 bg-accent text-white text-xs font-medium rounded-[5px] hover:bg-accent/90 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
      >
        {posting ? 'Posting…' : 'Post Note'}
      </button>
    </div>
  )
}
