'use client'

import { useState } from 'react'
import { toast } from 'sonner'

/**
 * Secure intake invitation (2026-09-22, §15): the broker types a carrier's
 * email; HeavyHaul Agent emails a link tied to that address (14 days) so the
 * carrier lands on the intake page already recognised.
 */
export function InviteCarrierButton() {
  const [open, setOpen] = useState(false)
  const [email, setEmail] = useState('')
  const [busy, setBusy] = useState(false)
  const [link, setLink] = useState<string | null>(null)
  async function send() {
    setBusy(true)
    try {
      const r = await fetch('/api/intake/invitations', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) })
      const json = await r.json().catch(() => ({}))
      if (!r.ok) throw new Error(json.error ?? 'Could not send the invitation.')
      setLink(json.link)
      toast.success(json.email_status === 'sent' ? `Invitation emailed to ${email}` : `Invitation recorded for ${email} — copy the link below`)
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not send the invitation.')
    } finally {
      setBusy(false)
    }
  }
  return (
    <div className="relative">
      <button onClick={() => { setOpen((v) => !v); setLink(null) }} className="rounded-lg border border-line bg-white px-4 py-2.5 text-sm font-semibold transition hover:border-navy-500">Invite a Carrier</button>
      {open && (
        <div className="absolute right-0 z-20 mt-2 w-80 rounded-xl border border-line bg-white p-3 shadow-lg">
          <p className="text-xs text-slate-body">Send a secure intake link to a carrier or dispatcher. It is tied to their email and expires in 14 days.</p>
          <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder="dispatch@carrier.com" className="mt-2 w-full rounded-lg border border-line px-3 py-2 text-sm" />
          <div className="mt-2 flex justify-end gap-2">
            <button onClick={() => setOpen(false)} className="rounded-lg px-3 py-1.5 text-xs font-bold text-slate-body">Close</button>
            <button onClick={send} disabled={busy || !email.includes('@')} className="rounded-lg bg-navy-900 px-3 py-1.5 text-xs font-bold text-white disabled:opacity-50">{busy ? 'Sending…' : 'Send invitation'}</button>
          </div>
          {link && <button onClick={() => { navigator.clipboard.writeText(link); toast.success('Link copied') }} className="mt-2 w-full truncate rounded-lg bg-paper px-2 py-1.5 text-left font-mono text-[10px] text-ink" title={link}>{link}</button>}
        </div>
      )}
    </div>
  )
}
