'use client'

import { COMPANY_CARD_PITCH } from '@/components/app/auto-participants-explainer'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { carrierRoleLabel } from '@/lib/domain/carrier-company'
import { CARRIER_COMPANY_ROLES, ROLE_LABELS } from '@/lib/domain/modes'
import type { CarrierCompanyInfo } from '@/lib/data/carrier-company'
import {
  AdminPicker, AuditCard, BulkInviteButton, CARD, ClosedView, CompanyHeader, CompanyProfileCard, CompanySettingsCard, ConnectCard, InviteMemberCard, MyRelationshipCard,
  OfficialDataCard, PendingRequestsCard, PendingView, VerifiedMembersCard, type RelationshipUiFlow,
} from '@/components/app/company-relationship/cards'

/**
 * Carrier Dashboard → Company Info (Nash, 2026-09-19). One more tab of the
 * same dashboard — same cards, same type, same buttons — not another app.
 *
 *   STATE 1  pending        verification status only, no management
 *   STATE 2  verified       read-only company information + my relationship
 *   STATE 3  company_admin  profile, settings, pending requests, verified
 *                           dispatchers, audit — company-scoped
 *   HeavyHaul admin         STATE 3 on any carrier, with a company picker
 *                           and the official-data editor; every action logged
 *
 * Cards are shared with the broker page; this file owns the carrier wording.
 */
const FLOW: RelationshipUiFlow = {
  apiUrl: '/api/cd/company-info',
  memberNoun: 'Carrier Dispatcher',
  memberNounPlural: 'Dispatchers',
  companyNoun: 'carrier',
  dashboardPath: '/cd-dashboard',
  roleLabel: carrierRoleLabel,
  auditLabels: {},
  inviteBlurb: 'People you already know work for this carrier. 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 create one with that email. Pick their role: every office role (Dispatcher, Safety Manager, Permit Manager, Accounting, Fleet Manager) has Carrier Dispatcher powers; Carrier Driver opens the driver app.',
  // D15 (2026-09-30): the carrier hands out five dispatcher-power titles and Carrier Driver.
  memberRoles: CARRIER_COMPANY_ROLES.map((r) => ({ value: r, label: ROLE_LABELS[r] })),
}

export function CompanyInfoTab({ info, viewer }: { info: CarrierCompanyInfo; 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`}>Company Info 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} />}
      {!company ? (
        info.isPlatformAdmin ? (
          <div className={`${CARD} border-dashed text-center text-sm text-slate-body`}>No carrier companies exist yet.</div>
        ) : (
          <ConnectCard title="Connect your carrier" intro="Tell us which carrier you dispatch for. The company confirms the relationship; until then your account stays connected but unverified." onDone={refresh} />
        )
      ) : (
        <>
          <CompanyHeader info={info} company={company} flow={FLOW} />
          {info.view === 'pending' && <PendingView info={info} company={company} flow={FLOW} onDone={refresh} />}
          {(info.view === 'rejected' || info.view === 'revoked') && <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} onDone={refresh} />
              <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">{COMPANY_CARD_PITCH}</p>
                  <p className="mt-1 text-xs text-slate-body">Dispatchers see only their own trips. A Company Auto-Participant is added to every applicable company trip from the day the rule is set, with their own role, and gets the usual trip notifications.</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} />}
              <AuditCard info={info} company={company} flow={FLOW} />
            </>
          )}
        </>
      )}
    </div>
  )
}
