'use client'

import { useState } from 'react'
import Link from 'next/link'
import type { BrokerageRollup } from '@/lib/data/broker-leads'
import { CARD, INPUT } from './shared'
import { useLeadKind } from './kind-context'

/** Brokerages with their lead funnel: "TQL: 182 leads, 40 invited, 6 signed up." */
export function BrokeragesTab({ rollups }: { rollups: BrokerageRollup[] }) {
  const cfg = useLeadKind()
  const carrier = cfg.kind === 'carrier'
  const noun = carrier ? 'companies' : 'brokerages'
  const [q, setQ] = useState('')
  const [onlyWithLeads, setOnly] = useState(true)
  const rows = rollups.filter((r) => (!onlyWithLeads || r.total > 0) && (!q || r.name.toLowerCase().includes(q.toLowerCase()) || (r.mc_number ?? '').includes(q)))
  const n = (r: BrokerageRollup, k: keyof BrokerageRollup['stages']) => r.stages[k] ?? 0
  return (
    <div className="space-y-4">
      <div className={`${CARD} flex flex-wrap items-center gap-3 text-xs`}>
        <input className={`${INPUT} w-64`} placeholder={carrier ? 'Search company' : 'Search brokerage or MC'} value={q} onChange={(e) => setQ(e.target.value)} />
        <label className="flex items-center gap-1"><input type="checkbox" checked={onlyWithLeads} onChange={(e) => setOnly(e.target.checked)} /> Only {noun} with leads</label>
        <span className="ml-auto text-neutral-500">{rows.length} {noun} · {rows.reduce((a, r) => a + r.total, 0)} leads</span>
      </div>
      <div className="overflow-x-auto rounded-2xl border bg-white">
        <table className="w-full text-left text-sm">
          <thead className="bg-neutral-50 text-[11px] uppercase tracking-wide text-neutral-500">
            <tr><th className="px-3 py-2">{carrier ? 'Company' : 'Brokerage'}</th><th className="px-3 py-2">State</th><th className="px-3 py-2">Verified</th><th className="px-3 py-2 text-right">Leads</th><th className="px-3 py-2 text-right">Not invited</th><th className="px-3 py-2 text-right">Invited</th><th className="px-3 py-2 text-right">Signed up</th><th className="px-3 py-2 text-right">{carrier ? 'Active' : 'Confirmed'}</th><th className="px-3 py-2 text-right">Lost</th></tr>
          </thead>
          <tbody className="divide-y">
            {rows.map((r) => (
              <tr key={r.id} className="hover:bg-neutral-50">
                <td className="px-3 py-2"><Link href={`${cfg.path}?tab=leads&brokerage=${encodeURIComponent(r.id)}`} className="font-semibold hover:underline">{r.name}</Link>{r.mc_number && <span className="text-xs text-neutral-400"> · MC {r.mc_number}</span>}</td>
                <td className="px-3 py-2 text-xs">{r.state ?? '—'}</td>
                <td className="px-3 py-2 text-[11px] text-neutral-500">{r.verification_status?.replace(/_/g, ' ') ?? '—'}</td>
                <td className="px-3 py-2 text-right font-semibold">{r.total}</td>
                <td className="px-3 py-2 text-right">{n(r, 'not_invited')}</td>
                <td className="px-3 py-2 text-right">{n(r, 'invited') + n(r, 'opened') + n(r, 'clicked')}</td>
                <td className="px-3 py-2 text-right">{n(r, 'signed_up')}</td>
                <td className="px-3 py-2 text-right text-green-700">{n(r, 'converted')}</td>
                <td className="px-3 py-2 text-right text-red-700">{n(r, 'bounced') + n(r, 'unsubscribed') + n(r, 'suppressed') + n(r, 'declined')}</td>
              </tr>
            ))}
            {rows.length === 0 && <tr><td colSpan={9} className="px-3 py-8 text-center text-sm text-neutral-500">No {noun} match.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  )
}
