'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { toast } from 'sonner'
import { getAckedWarnings } from '@/lib/ack'
import { StatusBadge } from '@/components/app/status-badge'
import { CompanyStatusChip, RiskTiles } from '@/components/app/risk-tiles'
import { ViewToggle } from '@/components/app/view-toggle'
import { demoPilotStatesIn } from '@/lib/demo/pilot-cars'
import { cityState, formatFullDate } from '@/lib/format'
import { STATUS_LABELS, resolveStatusForUser, type TripCompletion } from '@/lib/domain/status'
import type { BrokerPage, Trip, TripWarning } from '@/types/db'
import type { PermitLite, TripDriver } from '@/lib/data/dashboard-data'

/** Broker Dashboard — approved prototype layout on real data. */

const FILTERS = ['All', 'Waiting on Permits', 'Active', 'History'] as const
type Filter = (typeof FILTERS)[number]

/** Blocks ⇄ Table view, remembered per browser (Task 16). */
const VIEW_KEY = 'hha-dash-view'

export function BrokerDashboard({
  trips,
  warnings: allWarnings,
  brokerPage,
  permits,
  drivers,
  userId,
  completions,
  companyStatus,
}: {
  trips: Trip[]
  warnings: TripWarning[]
  brokerPage: BrokerPage | null
  permits: PermitLite[]
  drivers: TripDriver[]
  userId: string
  /** 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
}) {
  const [filter, setFilter] = useState<Filter>('All')
  const [copied, setCopied] = useState(false)

  const [view, setView] = useState<'blocks' | 'table'>('blocks')
  useEffect(() => {
    try {
      const saved = localStorage.getItem(VIEW_KEY)
      if (saved === 'table' || saved === 'blocks') setView(saved)
    } catch {
      // storage unavailable — keep default
    }
  }, [])
  function switchView(v: 'blocks' | 'table') {
    setView(v)
    try {
      localStorage.setItem(VIEW_KEY, v)
    } catch {
      // storage unavailable — selection lasts this session only
    }
  }

  // Per-user acknowledged warnings stay hidden for this user (Task 10).
  const [acked, setAcked] = useState<Set<string>>(new Set())
  useEffect(() => setAcked(getAckedWarnings(userId)), [userId])
  const warnings = allWarnings.filter((w) => !acked.has(w.id))

  const intakeUrl = brokerPage
    ? `${typeof window !== 'undefined' ? window.location.origin : ''}/intake/${brokerPage.slug}`
    : null

  const visible = trips.filter((t) => {
    switch (filter) {
      case 'All':
        return true
      case 'Waiting on Permits':
        return t.status === 'draft' || t.status === 'waiting_for_permits'
      case 'Active':
        return t.status === 'active'
      case 'History':
        return t.status === 'completed' || t.status === 'cancelled'
    }
  })

  function permitLine(t: Trip): string {
    const tripPermits = permits.filter((p) => p.trip_id === t.id)
    if (tripPermits.length === 0) {
      return t.status === 'active' ? 'No permits on file' : 'Waiting on permit upload'
    }
    const states = [...new Set(tripPermits.map((p) => p.state_code).filter(Boolean))]
    return `${tripPermits.length} permit${tripPermits.length === 1 ? '' : 's'} · ${states.join(', ')}`
  }
  /** Nash, 2026-09-13: the broker gets a visual reference that a pilot car is
      attached (hired by the dispatcher) — no contact details here. */
  function pilotBadge(t: Trip) {
    const states = [...new Set(permits.filter((p) => p.trip_id === t.id).map((p) => p.state_code).filter(Boolean))]
    const withPilot = demoPilotStatesIn(states)
    if (withPilot.length === 0) return null
    return (
      <span className="inline-flex items-center rounded-full bg-info-bg px-2 py-0.5 text-[10px] font-bold text-info ring-1 ring-inset ring-blue-200" title="A pilot car is attached to this trip for these states">
        🚗 Pilot car · {withPilot.join(', ')}
      </span>
    )
  }

  return (
    <main className="mx-auto max-w-6xl px-4 py-8">
      {/* Header row */}
      <div className="flex flex-wrap items-end justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold tracking-tight">Your oversize loads</h1>
          <p className="mt-1 text-sm text-slate-body">
            Give every oversize load its own permit workspace. Create a request, invite the
            dispatcher, and see permits in one place.
          </p>
          <CompanyStatusChip status={companyStatus} />
        </div>
        <div className="flex gap-3">
          {intakeUrl && (
            <button
              onClick={() => {
                navigator.clipboard.writeText(intakeUrl)
                setCopied(true)
                toast.success('Intake link copied')
                setTimeout(() => setCopied(false), 1800)
              }}
              className="rounded-lg border border-line bg-white px-4 py-2.5 text-sm font-semibold transition hover:border-navy-500"
            >
              {copied ? '✓ Copied' : 'Copy Intake Link'}
            </button>
          )}
          {/* Header keeps the approved three buttons (Nash, 2026-09-13
              screenshot): Copy Intake Link · + New Trip Request · + New Trip.
              "View Public Page →" lives on the intake card below. */}
          {/* Two ways to start a load, labelled so the difference is obvious
              now that they sit together (Task 101, 2026-09-09). The request
              goes to a carrier; the trip is the broker's own. */}
          <Link
            href="/fb-new-trip-request"
            title="Send a request to a carrier — they upload permits into the shared workspace"
            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 Request
          </Link>
          <Link
            href="/fb-new-trip"
            title="Create a trip of your own — no carrier needed, invite people later"
            className="rounded-lg border border-line bg-white px-4 py-2.5 text-sm font-semibold transition hover:border-navy-500"
          >
            + New Trip
          </Link>
        </div>
      </div>

      {/* "Where are the risks?" — the same six tiles the carrier dashboard has
          (Task 82, Nash 2026-09-08: "only the six boxes across the top").
          Counts use the acknowledged-filtered warnings this page already shows. */}
      <section className="mt-7">
        <h2 className="text-lg font-extrabold tracking-tight">Where are the risks?</h2>
        <div className="mt-3">
          <RiskTiles trips={trips} warnings={warnings} />
        </div>
      </section>

      {/* Warnings strip — all warnings across all trips, surfaced first */}
      {warnings.length > 0 && (
        <div className="mt-5 rounded-2xl border border-amber-200 bg-amber-50/60 p-4">
          <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-amber-800">
            ⚠ Warnings across your trips ({warnings.length})
          </p>
          <div className="mt-2.5 space-y-1.5">
            {warnings.slice(0, 4).map((w) => {
              const t = trips.find((x) => x.id === w.trip_id)
              return (
                <Link
                  key={w.id}
                  href={`/fb-trip-workspace/${trips.find((x) => x.id === w.trip_id)?.ref_code ?? w.trip_id}`}
                  className="flex items-center justify-between gap-3 rounded-lg bg-white px-3 py-2 text-sm ring-1 ring-line transition hover:ring-amber-brand"
                >
                  <span className="min-w-0 truncate">
                    <span className={`font-semibold ${w.severity === 'danger' ? 'text-danger' : 'text-warn'}`}>
                      {w.severity === 'danger' ? 'Urgent' : 'Warning'}:
                    </span>{' '}
                    {w.message}
                    {t && <span className="text-slate-body"> · {t.origin || '?'} → {t.destination || '?'}</span>}
                  </span>
                  <span className="shrink-0 text-xs font-bold text-navy-900">Open →</span>
                </Link>
              )
            })}
            {warnings.length > 4 && (
              <Link href="/alerts" className="block pt-1 text-center text-xs font-bold text-amber-800 hover:underline">
                View all {warnings.length} alerts →
              </Link>
            )}
          </div>
        </div>
      )}

      {/* Intake link card */}
      {brokerPage && (
        <div className="mt-6 flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-line bg-white p-5">
          <div className="min-w-0">
            <p className="text-[10px] font-bold uppercase tracking-[0.14em] text-slate-body/70">
              Your broker intake page
            </p>
            <p className="mt-1 truncate font-mono text-sm font-semibold text-navy-900">
              /intake/{brokerPage.slug}
            </p>
            <p className="mt-1 text-xs text-slate-body">
              Share this link with carriers — they can submit a rate confirmation without creating
              an account.
            </p>
          </div>
          <Link
            href={`/intake/${brokerPage.slug}`}
            target="_blank"
            className="rounded-lg bg-navy-900 px-4 py-2 text-xs font-bold text-white transition hover:bg-navy-800"
          >
            View Public Page →
          </Link>
        </div>
      )}

      {/* Filters + view toggle. Mobile QA 2026-09-13: chips wrap instead of
          clipping behind the toggle on a phone; the toggle keeps its own space. */}
      <div className="mt-8 flex flex-wrap items-center justify-between gap-3">
        <div className="flex min-w-0 flex-wrap gap-2">
          {FILTERS.map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`shrink-0 rounded-full px-4 py-2 text-sm font-semibold transition ${
                f === filter
                  ? 'bg-navy-900 text-white'
                  : 'bg-white text-slate-body ring-1 ring-line hover:text-ink'
              }`}
            >
              {f}
            </button>
          ))}
        </div>
        <ViewToggle view={view} onChange={switchView} />
      </div>

      {view === 'table' ? (
        <div className="mt-5 overflow-x-auto rounded-2xl border border-line bg-white">
          <table className="w-full min-w-[800px] text-sm">
            <thead>
              <tr className="border-b border-line text-left text-[11px] font-bold uppercase tracking-wide text-slate-body/70">
                {['Lane', 'Carrier', 'Unit', 'Driver', 'States', 'Permits', 'Status', ''].map((h) => (
                  <th key={h} className="px-4 py-3">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.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 (
                  <tr key={t.id} className="border-b border-line last:border-0 hover:bg-paper">
                    <td className="px-4 py-3.5 font-semibold">
                      {/* Lane as "City, ST → City, ST" — Nash: "so we don't
                          overload column one with too much text." */}
                      {cityState(t.origin) || '?'} → {cityState(t.destination) || '?'}
                      {tw.length > 0 && (
                        <p className="mt-0.5 text-[11px] font-medium text-warn">
                          ⚠ {tw.length} warning{tw.length === 1 ? '' : 's'}
                        </p>
                      )}
                    </td>
                    <td className="px-4 py-3.5">{t.carrier_name || '—'}</td>
                    <td className="px-4 py-3.5 font-mono text-xs">{t.unit_number || '—'}</td>
                    <td className="px-4 py-3.5">{driver?.name || '—'}</td>
                    <td className="px-4 py-3.5 font-mono text-xs">
                      {states.join(', ') || '—'}
                      {pilotBadge(t) && <span className="ml-1.5 font-sans">{pilotBadge(t)}</span>}
                    </td>
                    <td className="px-4 py-3.5 text-xs">{tripPermits.length > 0 ? tripPermits.length : 'None'}</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={`/fb-trip-workspace/${t.ref_code}`} className="text-xs font-bold text-info hover:underline">
                        Open
                      </Link>
                    </td>
                  </tr>
                )
              })}
              {visible.length === 0 && (
                <tr>
                  <td colSpan={8} className="px-4 py-10 text-center text-sm text-slate-body">
                    No trips in this view.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      ) : (
      <div className="mt-5 grid gap-4 md:grid-cols-2">
        {visible.map((t) => {
          const tripWarnings = warnings.filter((w) => w.trip_id === t.id)
          return (
            <Link
              key={t.id}
              href={`/fb-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">
                  <p className="truncate font-bold tracking-tight" title={`${t.origin} → ${t.destination}`}>
                    {cityState(t.origin) || 'Origin TBD'} → {cityState(t.destination) || 'Destination TBD'}
                  </p>
                  <p className="mt-0.5 truncate text-sm text-slate-body">
                    {t.commodity || 'Commodity TBD'}
                  </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>
                  Carrier: <span className="font-semibold text-ink">{t.carrier_name || 'TBD'}</span>
                </span>
                <span>{formatFullDate(t.updated_at)}</span>
              </div>
              <p className="mt-2 text-xs text-slate-body">{permitLine(t)}</p>
                {pilotBadge(t) && <p className="mt-1.5">{pilotBadge(t)}</p>}
              {tripWarnings.length > 0 && (
                <p className="mt-2 text-xs font-semibold text-warn">
                  ⚠ {tripWarnings.length} active warning{tripWarnings.length === 1 ? '' : 's'}
                </p>
              )}
              <p className="mt-3 text-xs font-bold text-navy-900 opacity-0 transition group-hover:opacity-100">
                Open trip workspace →
              </p>
            </Link>
          )
        })}
        {visible.length === 0 && (
          <div className="col-span-full rounded-2xl border border-dashed border-line p-10 text-center text-sm text-slate-body">
            {trips.length === 0
              ? 'No trips yet. Share your intake link with a carrier, or create a trip request yourself.'
              : 'No trips in this view.'}
          </div>
        )}
      </div>
      )}
    </main>
  )
}

/** Blocks ⇄ Table switch, shared style for both dashboards (Task 16). */
