'use client'

import { cityState } from '@/lib/format'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { STATUS_LABELS, resolveStatusForUser, type TripCompletion } from '@/lib/domain/status'
import { StatusBadge } from '@/components/app/status-badge'
import { ContactsPanel } from '@/components/app/contacts-panel'
import { ViewToggle } from '@/components/app/view-toggle'
import { demoPilotStatesIn } from '@/lib/demo/pilot-cars'
import { CompanyStatusChip, RiskTiles } from '@/components/app/risk-tiles'
import type { CarrierContact, Trip, TripWarning } from '@/types/db'
import type { PermitLite, TripDriver } from '@/lib/data/dashboard-data'

/**
 * Carrier Control Tower — "Where are the risks?"
 * Approved prototype layout on real data. Sections whose backend is not built
 * yet (Drivers, Fleet, Reports) show honest rollout placeholders.
 */

const TABS = [
  'All Trips',
  'Active Trips',
  'Pending Trips',
  // Nash, 2026-09-09: "We don't have a tab in there for completed trips… it
  // should be all trips, active, pending, and then history… Or we can call it
  // completed trips." Finished loads are reference material, so they get their
  // own tab and stay out of All Trips.
  'Completed Trips',
  'Needs Review',
  // Nash, 2026-09-09: "My contacts — instead of Fleet, should we have their
  // drivers?" He rejected unit history for this tab in the same breath, so it
  // holds the people a dispatcher works with (Task 98).
  'Drivers',
  'Reports',
] as const
type Tab = (typeof TABS)[number]

type DotState = 'Clear' | 'Warning' | 'Review'

const DOT_STYLES: Record<DotState, string> = {
  Clear: 'bg-ok-bg text-ok ring-green-200',
  Warning: 'bg-warn-bg text-warn ring-amber-200',
  Review: 'bg-danger-bg text-danger ring-red-200',
}

const SEV_STYLES: Record<TripWarning['severity'], string> = {
  danger: 'bg-danger-bg text-danger ring-red-200',
  warning: 'bg-warn-bg text-warn ring-amber-200',
  info: 'bg-info-bg text-info ring-blue-200',
}

const SEV_LABELS: Record<TripWarning['severity'], string> = {
  danger: 'Urgent',
  warning: 'Warning',
  info: 'Review',
}

export function CarrierDashboard({
  contacts,
  trips,
  warnings,
  permits,
  drivers,
  completions,
  companyStatus,
}: {
  trips: Trip[]
  warnings: TripWarning[]
  permits: PermitLite[]
  drivers: TripDriver[]
  /** Per-user completion (2026-09-07): the status shown is the one THIS user
      sees — a trip someone else completed stays active here until they mark it. */
  completions: Record<string, TripCompletion>
  /** Company verification status (Task 89) — optional chip under the title. */
  companyStatus?: { label: string; href: string; tone: 'ok' | 'pending' | 'none' } | null
  /** Saved drivers and brokers for the Drivers tab (Task 98). */
  contacts: { available: boolean; contacts: CarrierContact[] }
}) {
  const [tab, setTab] = useState<Tab>('All Trips')

  // Blocks ⇄ Table view, remembered per browser (Task 16).
  const [view, setView] = useState<'blocks' | 'table'>('table')
  useEffect(() => {
    try {
      const saved = localStorage.getItem('hha-dash-view')
      if (saved === 'table' || saved === 'blocks') setView(saved)
      // Mobile QA 2026-09-13: with no saved choice, a phone starts on Blocks —
      // the nine-column table only scrolls sideways there. The toggle and the
      // saved choice still win.
      else if (window.innerWidth < 640) setView('blocks')
    } catch {
      // storage unavailable — keep default
    }
  }, [])
  function switchView(v: 'blocks' | 'table') {
    setView(v)
    try {
      localStorage.setItem('hha-dash-view', v)
    } catch {
      // storage unavailable — selection lasts this session only
    }
  }

  // Bucket on the status THIS user sees, not the raw trip status (Task 97).
  // Completion is personal (Task 60) and the status column already renders the
  // resolved value, so filtering on `t.status` put a trip the dispatcher had
  // marked "Complete for me" in All Trips with the word "Completed" in its own
  // row — and would now have shown it in two tabs at once.
  const statusFor = (t: Trip) => resolveStatusForUser(t.status, completions[t.id])
  const open = trips.filter((t) => ['draft', 'waiting_for_permits', 'active'].includes(statusFor(t)))
  const active = trips.filter((t) => statusFor(t) === 'active')
  const pending = trips.filter((t) => ['draft', 'waiting_for_permits'].includes(statusFor(t)))
  // Same definition the broker dashboard's History filter uses, so one trip
  // can never be "history" on one dashboard and "open" on the other.
  const completed = trips
    .filter((t) => ['completed', 'cancelled'].includes(statusFor(t)))
    .slice()
    .sort((a, b) => (b.completed_at ?? b.updated_at).localeCompare(a.completed_at ?? a.updated_at))

  const rows =
    tab === 'Active Trips'
      ? active
      : tab === 'Pending Trips'
        ? pending
        : tab === 'Completed Trips'
          ? completed
          : open

  function dot(tripId: string, kinds: TripWarning['kind'][]): DotState {
    const relevant = warnings.filter((w) => w.trip_id === tripId && kinds.includes(w.kind))
    if (relevant.some((w) => w.severity === 'danger')) return 'Review'
    if (relevant.length > 0) return 'Warning'
    return 'Clear'
  }

  function tripLabel(t: Trip): string {
    return `${t.origin || '?'} → ${t.destination || '?'} · ${t.commodity || t.ref_code}`
  }

  return (
    <main className="mx-auto max-w-7xl px-4 py-8">
      <div className="flex flex-wrap items-end justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold tracking-tight">Where are the risks?</h1>
          <p className="mt-1 text-sm text-slate-body">
            Every permit, every trip, every driver question, and every compliance warning — in one
            place.
          </p>
          <CompanyStatusChip status={companyStatus} />
        </div>
        <Link
          href="/cd-new-trip"
          className="rounded-lg bg-amber-brand px-4 py-2.5 text-sm font-bold text-navy-950 shadow-sm transition hover:bg-amber-deep"
        >
          + New Trip
        </Link>
      </div>

      {/* Summary cards — shared with the broker dashboard (Task 82) */}
      <div className="mt-7">
        <RiskTiles trips={trips} warnings={warnings} />
      </div>

      {/* Tabs. Mobile QA 2026-09-13: wrap instead of scrolling sideways so
          every tab stays visible on a phone or iPad. */}
      <div className="mt-8 flex flex-wrap gap-1 border-b border-line">
        {TABS.map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={`border-b-2 px-3 py-2.5 text-sm font-semibold transition sm:px-4 ${
              t === tab ? 'border-amber-brand text-ink' : 'border-transparent text-slate-body hover:text-ink'
            }`}
          >
            {t}
            {t === 'Needs Review' && warnings.length > 0 && (
              <span className="ml-1.5 rounded-full bg-danger-bg px-1.5 py-0.5 text-[10px] font-bold text-danger">
                {warnings.length}
              </span>
            )}
          </button>
        ))}
      </div>

      {tab === 'Needs Review' ? (
        /* The safety team's daily operating list */
        <div className="mt-6 space-y-2.5">
          <p className="text-sm text-slate-body">
            Anything that requires attention, surfaced first — the safety team&apos;s daily
            operating list.
          </p>
          {warnings.length === 0 && (
            <div className="rounded-2xl border border-dashed border-line bg-white p-10 text-center text-sm text-slate-body">
              Nothing needs review right now. Warnings appear here as permits are uploaded and
              processed.
            </div>
          )}
          {warnings.map((w) => {
            const trip = trips.find((t) => t.id === w.trip_id)
            return (
              <div
                key={w.id}
                className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-line bg-white p-4"
              >
                <div className="flex items-center gap-3">
                  <span
                    className={`rounded-full px-2.5 py-1 text-[10px] font-bold uppercase ring-1 ring-inset ${SEV_STYLES[w.severity]}`}
                  >
                    {SEV_LABELS[w.severity]}
                  </span>
                  <div>
                    <p className="text-sm font-bold">{w.message}</p>
                    <p className="text-xs text-slate-body">{trip ? tripLabel(trip) : w.trip_id}</p>
                  </div>
                </div>
                <Link
                  href={`/cd-trip-workspace/${trips.find((x) => x.id === w.trip_id)?.ref_code ?? w.trip_id}`}
                  className="rounded-lg bg-navy-900 px-3 py-1.5 text-xs font-bold text-white hover:bg-navy-800"
                >
                  Open Trip
                </Link>
              </div>
            )
          })}
        </div>
      ) : tab === 'Reports' ? (
        <ReportsTab trips={trips} warnings={warnings} permits={permits} drivers={drivers} />
      ) : tab === 'Drivers' ? (
        <ContactsPanel available={contacts.available} contacts={contacts.contacts} />
      ) : view === 'blocks' ? (
        /* Blocks view (Task 16) */
        <>
          <div className="mt-4 flex justify-end">
            <ViewToggle view={view} onChange={switchView} />
          </div>
          <div className="mt-3 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {rows.map((t) => {
              const tripPermits = permits.filter((p) => p.trip_id === t.id)
              const states = [...new Set(tripPermits.map((p) => p.state_code).filter(Boolean))]
              const driver = drivers.find((d) => d.trip_id === t.id)
              const tw = warnings.filter((w) => w.trip_id === t.id)
              return (
                <Link
                  key={t.id}
                  href={`/cd-trip-workspace/${t.ref_code}`}
                  className="group rounded-2xl border border-line bg-white p-5 transition hover:border-amber-brand/60 hover:shadow-md"
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      {/* Blocks show "City, ST → City, ST"; the full address
                          stays in the tooltip and in the workspace. */}
                      <p className="truncate font-bold tracking-tight" title={`${t.origin} → ${t.destination}`}>
                        {cityState(t.origin) || '?'} → {cityState(t.destination) || '?'}
                      </p>
                      <p className="mt-0.5 truncate text-sm text-slate-body">
                        {t.commodity || 'Commodity TBD'}
                        {t.unit_number ? ` · Unit ${t.unit_number}` : ''}
                      </p>
                    </div>
                    <StatusBadge status={t.status} policy={t.permit_policy} />
                  </div>
                  <div className="mt-4 flex items-center justify-between border-t border-line pt-3.5 text-xs text-slate-body">
                    <span>
                      Driver: <span className="font-semibold text-ink">{driver?.name || '—'}</span>
                    </span>
                    <span className="font-mono">{states.join(' ') || '—'}</span>
                  </div>
                  {/* Nash, 2026-09-13: New Mexico (and Arizona) carry a hired pilot car. */}
                  {demoPilotStatesIn(states).length > 0 && (
                    <div className="mt-2 text-[10px] font-bold text-info">🚗 Pilot car attached · {demoPilotStatesIn(states).join(', ')} — John Cena (driver) · Mark Cuban (dispatch)</div>
                  )}
                  {tw.length > 0 && (
                    <p className="mt-2 text-xs font-semibold text-warn">
                      ⚠ {tw.length} warning{tw.length === 1 ? '' : 's'}
                    </p>
                  )}
                </Link>
              )
            })}
            {rows.length === 0 && (
              <div className="col-span-full rounded-2xl border border-dashed border-line bg-white p-10 text-center text-sm text-slate-body">
                {tab === 'Completed Trips'
                  ? 'No completed trips yet.'
                  : 'No trips in this view. Create one or accept a broker invitation from your email.'}
              </div>
            )}
          </div>
        </>
      ) : (
        /* Trip table */
        <>
        <div className="mt-4 flex justify-end">
          <ViewToggle view={view} onChange={switchView} />
        </div>
        <div className="mt-3 overflow-x-auto rounded-2xl border border-line bg-white">
          <table className="w-full min-w-[900px] text-sm">
            <thead>
              <tr className="border-b border-line text-left text-[11px] font-bold uppercase tracking-wide text-slate-body/70">
                {['Driver', 'Unit', 'Lane', 'States', 'Permits', 'Curfew', 'Escort', 'Status', ''].map((h) => (
                  <th key={h} className="px-4 py-3">
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((t) => {
                const tripPermits = permits.filter((p) => p.trip_id === t.id)
                const states = [...new Set(tripPermits.map((p) => p.state_code).filter(Boolean))]
                const driver = drivers.find((d) => d.trip_id === t.id)
                const dims = warnings.find(
                  (w) => w.trip_id === t.id && w.kind === 'dimension_mismatch',
                )
                return (
                  <tr key={t.id} className="border-b border-line last:border-0 hover:bg-paper">
                    <td className="px-4 py-3.5 font-semibold">
                      {driver?.name || driver?.email || '—'}
                      {dims && <p className="mt-0.5 text-[11px] font-medium text-warn">⚠ {dims.message}</p>}
                    </td>
                    <td className="px-4 py-3.5 font-mono text-xs">{t.unit_number || '—'}</td>
                    <td className="px-4 py-3.5">
                      {t.origin || '?'} → {t.destination || '?'}
                    </td>
                    <td className="px-4 py-3.5 font-mono text-xs">
                      {states.join(', ') || '—'}
                      {demoPilotStatesIn(states).length > 0 && (
                        <span className="ml-1.5 rounded-full bg-info-bg px-2 py-0.5 font-sans text-[10px] font-bold text-info ring-1 ring-inset ring-blue-200" title="John Cena (driver) · Mark Cuban (dispatch)">🚗 Pilot · {demoPilotStatesIn(states).join(', ')}</span>
                      )}
                    </td>
                    <td className="px-4 py-3.5 text-xs">
                      {tripPermits.length > 0 ? `${tripPermits.length} uploaded` : 'None'}
                    </td>
                    <td className="px-4 py-3.5">
                      <Dot v={dot(t.id, ['curfew'])} />
                    </td>
                    <td className="px-4 py-3.5">
                      <Dot v={dot(t.id, ['escort'])} />
                    </td>
                    <td className="px-4 py-3.5 text-xs font-semibold">{STATUS_LABELS[resolveStatusForUser(t.status, completions[t.id])]}</td>
                    <td className="px-4 py-3.5">
                      <Link href={`/cd-trip-workspace/${t.ref_code}`} className="text-xs font-bold text-info hover:underline">
                        Open
                      </Link>
                    </td>
                  </tr>
                )
              })}
              {rows.length === 0 && (
                <tr>
                  <td colSpan={9} className="px-4 py-10 text-center text-sm text-slate-body">
                    {tab === 'Completed Trips'
                      ? 'No completed trips yet.'
                      : 'No trips in this view. Create one or accept a broker invitation from your email.'}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
        </>
      )}
    </main>
  )
}

/** Reports — real CSV exports built from the data already on this page. */
function ReportsTab({
  trips,
  warnings,
  permits,
  drivers,
}: {
  trips: Trip[]
  warnings: TripWarning[]
  permits: PermitLite[]
  drivers: TripDriver[]
}) {
  function downloadCsv(name: string, header: string[], rows: string[][]) {
    const esc = (v: string) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v)
    const csv = [header, ...rows].map((r) => r.map(esc).join(',')).join('\n')
    const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }))
    const a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()
    URL.revokeObjectURL(url)
  }

  const reports = [
    {
      title: 'Trips report',
      desc: `${trips.length} trips — lane, carrier, unit, driver, states, permits, status`,
      run: () =>
        downloadCsv(
          'trips-report.csv',
          ['Ref', 'Origin', 'Destination', 'Commodity', 'Carrier', 'Unit', 'Driver', 'States', 'Permits', 'Status', 'Created'],
          trips.map((t) => {
            const tp = permits.filter((p) => p.trip_id === t.id)
            return [
              t.ref_code,
              t.origin,
              t.destination,
              t.commodity,
              t.carrier_name,
              t.unit_number ?? '',
              drivers.find((d) => d.trip_id === t.id)?.name ?? '',
              [...new Set(tp.map((p) => p.state_code))].join(' '),
              String(tp.length),
              t.status,
              t.created_at.slice(0, 10),
            ]
          }),
        ),
    },
    {
      title: 'Warnings report',
      desc: `${warnings.length} active warnings — severity, kind, message, trip`,
      run: () =>
        downloadCsv(
          'warnings-report.csv',
          ['Severity', 'Kind', 'Message', 'Trip', 'Created'],
          warnings.map((w) => {
            const t = trips.find((x) => x.id === w.trip_id)
            return [
              w.severity,
              w.kind,
              w.message,
              t ? `${t.origin} -> ${t.destination} (${t.ref_code})` : w.trip_id,
              w.created_at.slice(0, 10),
            ]
          }),
        ),
    },
    {
      title: 'Permits report',
      desc: `${permits.length} permits — state, number, dates, trip`,
      run: () =>
        downloadCsv(
          'permits-report.csv',
          ['State', 'Permit #', 'Effective', 'Expires', 'Trip'],
          permits.map((p) => {
            const t = trips.find((x) => x.id === p.trip_id)
            return [
              p.state_code,
              p.permit_number ?? '',
              p.effective_date ?? '',
              p.expiration_date ?? '',
              t ? `${t.origin} -> ${t.destination} (${t.ref_code})` : p.trip_id,
            ]
          }),
        ),
    },
  ]

  return (
    <div className="mt-6 grid gap-4 md:grid-cols-3">
      {reports.map((r) => (
        <div key={r.title} className="rounded-2xl border border-line bg-white p-6">
          <h3 className="font-bold tracking-tight">{r.title}</h3>
          <p className="mt-1.5 text-xs leading-relaxed text-slate-body">{r.desc}</p>
          <button
            onClick={r.run}
            className="mt-4 w-full rounded-lg bg-navy-900 py-2 text-xs font-bold text-white transition hover:bg-navy-800"
          >
            ⬇ Download CSV
          </button>
        </div>
      ))}
      <p className="col-span-full text-xs text-slate-body/70">
        Exports include everything visible to your account right now. Scheduled and PDF reports
        arrive in a later phase.
      </p>
    </div>
  )
}

function Dot({ v }: { v: DotState }) {
  return (
    <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1 ring-inset ${DOT_STYLES[v]}`}>
      {v}
    </span>
  )
}
