'use client'

import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { BROKER_AUDIT_LABELS, brokerRoleLabel } from '@/lib/domain/broker-company'
import type { BrokerCompanyInfo } from '@/lib/data/broker-company'
import type { PersonRow } from '@/lib/data/carrier-company'
import {
  AdminPicker, AuditCard, BTN, BTN_SOFT, Badge, CARD, ClosedView, CompanyHeader, CompanyProfileCard, CompanySettingsCard, ConnectCard,
  BulkInviteButton, InviteMemberCard, MyRelationshipCard, OfficialDataCard, PendingRequestsCard, PendingView, Row, VerifiedMembersCard, call, fmt, type RelationshipUiFlow,
} from '@/components/app/company-relationship/cards'

/**
 * Broker Dashboard → Company Info (Nash, 2026-09-19). Broker-specific page:
 * its own route, its own API, broker wording — the cards are shared with
 * the carrier page, the flow below is what makes them broker.
 *
 *   none                  connect to a broker company (MC number)
 *   historical_confirm    "We found your existing broker relationship" —
 *                         yes / no, no verification email needed on yes
 *   pending               waiting for the company; resend / status / support
 *   manual_review         HeavyHaul Agent is reviewing
 *   verified              read-only company + my relationship
 *   company_admin         management: pending requests, verified agents,
 *                         settings, verification log, audit
 *   HeavyHaul admin       management on any broker company + pre-verified
 *                         contacts + official-data editor
 */
const FLOW: RelationshipUiFlow = {
  apiUrl: '/api/fb/company-info',
  memberNoun: 'Freight Broker',
  memberNounPlural: 'Freight Brokers',
  companyNoun: 'broker company',
  dashboardPath: '/fb-dashboard',
  roleLabel: brokerRoleLabel,
  auditLabels: BROKER_AUDIT_LABELS,
  inviteBlurb: 'People you already know work for this broker company. They are verified immediately — no request, no approval step — and receive an invitation email. Without a HeavyHaul Agent account yet, they are verified the moment they sign up with that email.',
}

export function BrokerCompanyTab({ info, viewer }: { info: BrokerCompanyInfo; viewer: { name: string; email: string } }) {
  const router = useRouter()
  const refresh = () => router.refresh()
  if (!info.available) {
    return <div className={`mt-6 ${CARD} border-dashed text-center text-sm text-slate-body`}>Broker Company needs database migration 0013 (company verification). Ask HeavyHaul Agent support.</div>
  }
  const { company } = info
  return (
    <div className="mt-6 space-y-4">
      {info.isPlatformAdmin && <AdminPicker info={info} flow={FLOW} />}
      {info.view === 'historical_confirm' && info.lead ? (
        <HistoricalConfirmCard info={info} onDone={refresh} />
      ) : !company ? (
        info.isPlatformAdmin ? (
          <div className={`${CARD} border-dashed text-center text-sm text-slate-body`}>No broker companies exist yet.</div>
        ) : (
          <ConnectCard title="Connect to your broker company" intro="Enter the MC number of the broker company you represent. We identify the company, you confirm it, and the company verifies your relationship." onDone={refresh} />
        )
      ) : (
        <>
          <CompanyHeader info={info} company={company} flow={FLOW} />
          {info.view === 'pending' && <PendingView info={info} company={company} flow={FLOW} onDone={refresh} />}
          {info.view === 'manual_review' && <ManualReviewCard info={info} />}
          {(info.view === 'rejected' || info.view === 'revoked' || info.view === 'no_longer_current') && <ClosedView info={info} flow={FLOW} onDone={refresh} />}
          {info.view === 'verified' && (
            <>
              <CompanyProfileCard company={company} />
              <MyRelationshipCard info={info} viewer={viewer} flow={FLOW} />
            </>
          )}
          {info.view === 'company_admin' && (
            <>
              <CompanyProfileCard company={company} />
              {info.membership && <MyRelationshipCard info={info} viewer={viewer} flow={FLOW} />}
              <PendingRequestsCard info={info} company={company} flow={FLOW} onDone={refresh} />
              <VerifiedMembersCard info={info} company={company} flow={FLOW} onDone={refresh} headerAction={<BulkInviteButton company={company} flow={FLOW} onDone={refresh} />} />
              <InviteMemberCard
                company={company}
                flow={FLOW}
                invited={[
                  ...info.invitations,
                  ...info.leads.filter((l) => l.claim_status === 'unclaimed' && l.invitation_status === 'invited').map((l) => ({ id: l.id, name: [l.first_name, l.last_name].filter(Boolean).join(' ') || null, email: l.email, invitedAt: l.invited_at })),
                ]}
                onDone={refresh}
              />
              <HistoricalListsCard info={info} />
              <div className={`${CARD} flex flex-wrap items-center justify-between gap-3`}>
                <div>
                  <h3 className="font-bold tracking-tight">Company Auto-Participants</h3>
                  <p className="mt-1 text-xs text-slate-body">Who the company adds to every applicable trip automatically.</p>
                </div>
                <Link href="/settings/auto-participants" className="rounded-lg bg-navy-900 px-3 py-1.5 text-xs font-bold text-white transition hover:bg-navy-800">Company Auto-Participants</Link>
              </div>
              <CompanySettingsCard company={company} flow={FLOW} onDone={refresh} />
              {info.isPlatformAdmin && <OfficialDataCard company={company} flow={FLOW} onDone={refresh} />}
              {info.isPlatformAdmin && <LeadsCard info={info} />}
              <VerificationLogCard info={info} />
              <AuditCard info={info} company={company} flow={FLOW} />
            </>
          )}
        </>
      )}
    </div>
  )
}

/** §14 — "We Found Your Existing Broker Relationship". */
function HistoricalConfirmCard({ info, onDone }: { info: BrokerCompanyInfo; onDone: () => void }) {
  const lead = info.lead!
  const [busy, setBusy] = useState<'yes' | 'no' | null>(null)
  async function answer(decision: 'yes' | 'no') {
    setBusy(decision)
    try {
      const r = await call(FLOW.apiUrl, { op: 'historical_confirm', decision })
      toast.success(decision === 'yes' ? `You are now a verified Freight Broker for ${r.company}.` : 'Noted — enter the MC number of the company you represent now.')
      onDone()
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not record your answer.')
    } finally {
      setBusy(null)
    }
  }
  const name = lead.broker_company_name || info.company?.display_name || 'this broker company'
  return (
    <div className={`${CARD} border-amber-200`}>
      <Badge tone="pending">Pre-verified relationship found</Badge>
      <h3 className="mt-2 text-lg font-extrabold tracking-tight">We Found Your Existing Broker Relationship</h3>
      <dl className="mt-3 grid gap-3 sm:grid-cols-3">
        <Row label="Broker Company" value={name} />
        <Row label="MC Number" value={lead.mc_number ? `MC ${lead.mc_number}` : null} />
        <Row label="USDOT" value={lead.usdot_number} />
      </dl>
      <p className="mt-3 text-sm text-slate-body">Our records show that you previously represented this broker company.</p>
      <p className="mt-1 text-sm font-semibold text-ink">Do you still represent {name}?</p>
      <div className="mt-4 flex flex-wrap gap-2">
        <button onClick={() => answer('yes')} disabled={!!busy} className={BTN}>{busy === 'yes' ? 'Confirming…' : 'Yes, I Still Represent This Company'}</button>
        <button onClick={() => answer('no')} disabled={!!busy} className={BTN_SOFT}>{busy === 'no' ? 'Saving…' : 'No, I No Longer Represent This Company'}</button>
      </div>
      <p className="mt-3 text-[11px] text-slate-body/70">Yes verifies your relationship right away (historical record + your confirmation). No keeps the record on file and lets you connect to a different company.</p>
    </div>
  )
}

function ManualReviewCard({ info }: { info: BrokerCompanyInfo }) {
  return (
    <div className={CARD}>
      <h3 className="font-bold tracking-tight">Relationship: Under Review by HeavyHaul Agent</h3>
      <p className="mt-2 text-sm text-slate-body">
        Your request could not be verified automatically{info.claim?.review_reason ? ` (${info.claim.review_reason.replace(/_/g, ' ').replace(/,/g, ', ')})` : ''}. HeavyHaul Agent is reviewing it and will email you.
      </p>
      {info.claim?.info_request && <p className="mt-2 rounded-lg bg-amber-50 p-3 text-xs text-amber-800">Note from the reviewer: {info.claim.info_request}</p>}
    </div>
  )
}

function PeopleList({ title, rows, badge, tone }: { title: string; rows: PersonRow[]; badge: string; tone: 'pending' | 'none' | 'danger' }) {
  if (rows.length === 0) return null
  return (
    <div>
      <p className="text-[11px] font-bold uppercase tracking-wide text-slate-body/70">{title} ({rows.length})</p>
      <ul className="mt-1.5 space-y-1.5 text-xs text-slate-body">
        {rows.map((p) => (
          <li key={p.membershipId} className="flex flex-wrap items-center justify-between gap-2 rounded-lg bg-paper px-3 py-2">
            <span><span className="font-semibold text-ink">{p.name}</span> · {p.email}</span>
            <span><Badge tone={tone}>{badge}</Badge> {fmt(p.requestedAt)}</span>
          </li>
        ))}
      </ul>
    </div>
  )
}

/** Broker-only relationship states beside the pending queue (§38). */
function HistoricalListsCard({ info }: { info: BrokerCompanyInfo }) {
  if (info.awaitingConfirmation.length + info.noLongerCurrent.length + info.manualReview.length === 0) return null
  return (
    <div className={`${CARD} space-y-4`}>
      <h3 className="font-bold tracking-tight">Historical &amp; Review States</h3>
      <PeopleList title="Awaiting Historical Confirmation" rows={info.awaitingConfirmation} badge="Awaiting confirmation" tone="pending" />
      <PeopleList title="Manual Review" rows={info.manualReview} badge="Manual review" tone="pending" />
      <PeopleList title="No Longer Current" rows={info.noLongerCurrent} badge="No longer current" tone="none" />
    </div>
  )
}

/** HeavyHaul admin: pre-verified broker contacts for this company (§18, §38). */
function LeadsCard({ info }: { info: BrokerCompanyInfo }) {
  const [open, setOpen] = useState(false)
  const counts = {
    unclaimed: info.leads.filter((l) => l.claim_status === 'unclaimed').length,
    claimed: info.leads.filter((l) => l.claim_status === 'claimed').length,
    review: info.leads.filter((l) => l.claim_status === 'manual_review').length,
  }
  return (
    <div className={`${CARD} border-blue-200`}>
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="flex items-center gap-2"><h3 className="font-bold tracking-tight">Pre-Verified Broker Contacts</h3><Badge tone="info">HeavyHaul Agent Admin</Badge></div>
        <button onClick={() => setOpen((v) => !v)} className="text-xs font-bold text-info hover:underline">{open ? 'Hide' : 'Show'} ({info.leads.length})</button>
      </div>
      <p className="mt-1 text-xs text-slate-body">Historical relationships from our business records — evidence, not accounts. Unclaimed {counts.unclaimed} · Claimed {counts.claimed} · Manual review {counts.review}.</p>
      {open && (
        <div className="mt-3 overflow-x-auto rounded-xl border border-line">
          <table className="w-full min-w-[640px] text-xs">
            <thead>
              <tr className="border-b border-line text-left text-[10px] font-bold uppercase tracking-wide text-slate-body/70">
                {['Name', 'Email', 'Phone', 'Claim', 'Confirmation', 'Invitation'].map((h) => <th key={h} className="px-3 py-2">{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {info.leads.map((l) => (
                <tr key={l.id} className="border-b border-line last:border-0">
                  <td className="px-3 py-2 font-semibold">{[l.first_name, l.last_name].filter(Boolean).join(' ') || '—'}</td>
                  <td className="px-3 py-2">{l.email}</td>
                  <td className="px-3 py-2">{l.phone ?? '—'}</td>
                  <td className="px-3 py-2">{l.claim_status.replace('_', ' ')}{l.manual_review_reason ? ` · ${l.manual_review_reason}` : ''}</td>
                  <td className="px-3 py-2">{l.relationship_confirmation_status.replace(/_/g, ' ')}</td>
                  <td className="px-3 py-2">{l.invitation_status.replace('_', ' ')}</td>
                </tr>
              ))}
              {info.leads.length === 0 && <tr><td colSpan={6} className="px-3 py-4 text-center text-slate-body">No pre-verified contacts for this company.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

/** §35 — was the verification sent, to whom, when, which template version, what happened. */
function VerificationLogCard({ info }: { info: BrokerCompanyInfo }) {
  const [open, setOpen] = useState(false)
  return (
    <div className={CARD}>
      <div className="flex flex-wrap items-center justify-between gap-2">
        <h3 className="font-bold tracking-tight">Verification Emails</h3>
        <button onClick={() => setOpen((v) => !v)} className="text-xs font-bold text-info hover:underline">{open ? 'Hide' : 'Show'} log ({info.verificationLog.length})</button>
      </div>
      {open && (
        <div className="mt-3 overflow-x-auto rounded-xl border border-line">
          <table className="w-full min-w-[760px] text-xs">
            <thead>
              <tr className="border-b border-line text-left text-[10px] font-bold uppercase tracking-wide text-slate-body/70">
                {['Sent', 'Requester', 'To', 'Template', 'Delivery', 'Result'].map((h) => <th key={h} className="px-3 py-2">{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {info.verificationLog.map((e) => (
                <tr key={e.id} className="border-b border-line last:border-0">
                  <td className="px-3 py-2">{new Date(e.sent_at).toLocaleString()}</td>
                  <td className="px-3 py-2 font-semibold">{e.requester_label ?? '—'}</td>
                  <td className="px-3 py-2">{e.recipient}</td>
                  <td className="px-3 py-2">{e.template_key} v{e.template_version ?? 0} · {e.kind}</td>
                  <td className="px-3 py-2">{e.delivery_status.replace(/_/g, ' ')}{e.error ? ` · ${e.error}` : ''}</td>
                  <td className="px-3 py-2"><Badge tone={e.final_result === 'approved' ? 'ok' : e.final_result === 'pending' ? 'pending' : 'danger'}>{e.final_result}</Badge></td>
                </tr>
              ))}
              {info.verificationLog.length === 0 && <tr><td colSpan={6} className="px-3 py-4 text-center text-slate-body">No verification emails yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
