import { notFound } from 'next/navigation'
import { AppShell } from '@/components/app/app-shell'
import { BrokerDashboard } from '@/app/fb-dashboard/broker-dashboard'
import { BrokerTripView } from '@/app/fb-trip-workspace/[ref]/broker-trip-view'
import { CarrierDashboard } from '@/app/cd-dashboard/carrier-dashboard'
import { CarrierTripView } from '@/app/cd-trip-workspace/[ref]/carrier-trip-view'
import { PilotCompanyDashboard } from '@/app/pd-dashboard/pilot-company-dashboard'
import { PilotAssignmentWorkspace } from '@/components/app/pilot-assignment/pilot-assignment-workspace'
import { PilotDriverView } from '@/app/pc-dashboard/pilot-driver-view'
import { DriverView } from '@/app/ct-dashboard/driver-view'
import { BrokerRequestForm } from '@/app/fb-new-trip-request/broker-request-form'
import { PrivateTripForm } from '@/app/pd-new-trip/private-trip-form'
import type { CarrierContact } from '@/types/db'
import { DEMO_PILOT_ASSIGNMENTS } from '@/lib/demo/pilot'
import { demoTripFor } from '@/lib/demo/pilot-agent'
import { EMPTY_COMPLETION } from '@/lib/domain/status'
import type { BrokerPage, Permit, Profile, Trip, TripParticipant, TripWarning } from '@/types/db'

/**
 * DEVELOPMENT-ONLY responsive preview of the role pages on demo data (Nash,
 * 2026-09-13: "Test all freight broker pages for the mobile view… cell phone
 * and also on iPad", then "check the carrier dispatch pages and the pilot
 * dispatch pages" the same way). No session, no database — each role's
 * dashboard and trip view rendered with demo trips so the layout can be
 * checked in the browser at phone and tablet widths. Returns 404 outside
 * `next dev`.
 *
 *   /dev-preview/fb/dashboard · /dev-preview/fb/trip · /dev-preview/fb/new-trip-request
 *   /dev-preview/cd/dashboard · /dev-preview/cd/trip
 *   /dev-preview/pd/dashboard · /dev-preview/pd/trip
 *   /dev-preview/pc/dashboard · /dev-preview/pc/trip
 *   /dev-preview/ct/trip (carrier truck driver app, admin preview)
 */
export default async function RoleDevPreview({ params }: { params: Promise<{ role: string; page: string }> }) {
  if (process.env.NODE_ENV !== 'development') notFound()
  const { role, page } = await params

  const profile: Profile =
    role === 'fb'
      ? { id: 'dev-preview-broker', email: 'broker@example.com', full_name: 'Preview Broker', phone: null, company_name: 'Summit Freight Brokerage', default_role: 'broker', created_at: '2026-09-01T00:00:00.000Z' }
      : { id: 'dev-preview-dispatch', email: 'dispatch@example.com', full_name: 'Preview Dispatcher', phone: null, company_name: 'Ridgeline Heavy Haul', default_role: 'dispatcher', created_at: '2026-09-01T00:00:00.000Z' }
  const trips: Trip[] = DEMO_PILOT_ASSIGNMENTS.map(demoTripFor)
  const permits: Permit[] = DEMO_PILOT_ASSIGNMENTS.flatMap((a) =>
    a.permits.map((p) => ({
      id: p.id,
      trip_id: a.id,
      document_id: null,
      state_code: p.state,
      permit_number: p.permitNumber,
      effective_date: p.effective,
      expiration_date: p.expires,
      permit_length_in: null,
      permit_width_in: null,
      permit_height_in: null,
      permit_weight_lbs: null,
      extraction: null,
      extraction_status: 'processed',
      created_at: `${a.createdAt}T09:00:00.000Z`,
    })),
  )
  const warnings: TripWarning[] = [
    { id: 'w-1', trip_id: 'asg-2', permit_id: 'p-5', kind: 'expiring', severity: 'warning', message: 'WV-OS-30117 expires in 3 days', resolved: false, created_at: '2026-09-12T09:00:00.000Z' },
    { id: 'w-2', trip_id: 'asg-1', permit_id: 'p-1', kind: 'dimension_mismatch', severity: 'danger', message: "Permit height 15'0\" is below the overall 15'6\"", resolved: false, created_at: '2026-09-12T09:00:00.000Z' },
  ]
  const drivers = DEMO_PILOT_ASSIGNMENTS.map((a) => ({ trip_id: a.id, name: a.carrierDriver.name, email: a.carrierDriver.email }))
  const completions = Object.fromEntries(trips.map((t) => [t.id, EMPTY_COMPLETION]))

  if (role === 'pc' && page === 'dashboard') {
    return (
      <AppShell profile={profile}>
        <PilotDriverView />
      </AppShell>
    )
  }
  if (role === 'pc' && page === 'trip') {
    return (
      <AppShell profile={profile}>
        <PilotAssignmentWorkspace assignmentKey="HH-2041" as="pilot_driver" isAdmin />
      </AppShell>
    )
  }

  if (role === 'pd' && page === 'new-trip') {
    return (
      <AppShell profile={profile}>
        <main className="mx-auto max-w-2xl px-4 py-8">
          <h1 className="text-2xl font-bold tracking-tight">Create a private trip</h1>
          <p className="mt-1 text-sm text-neutral-600">Your own workspace for a job — store the permit copies, ask the agent, order routes and keep the history. Nobody is invited until you share it.</p>
          <PrivateTripForm />
        </main>
      </AppShell>
    )
  }

  if (role === 'pd' && page === 'dashboard') {
    return (
      <AppShell profile={profile}>
        <PilotCompanyDashboard
          billing={{ routePurchases: [], routeCredits: { planName: 'Free', included: 1, used: 0, remaining: 1 }, internal: true }}
          settings={{ userId: profile.id, languages: ['en'], primary: 'en' }}
        />
      </AppShell>
    )
  }
  if (role === 'pd' && page === 'trip') {
    return (
      <AppShell profile={profile}>
        <PilotAssignmentWorkspace assignmentKey="HH-2041" as="pilot_company" isAdmin />
      </AppShell>
    )
  }

  if (role === 'cd' && page === 'dashboard') {
    return (
      <AppShell profile={profile}>
        <CarrierDashboard
          trips={trips}
          warnings={warnings}
          permits={permits}
          drivers={drivers}
          completions={completions}
          companyStatus={{ label: 'Approved company agent · Ridgeline Heavy Haul · Dispatcher', href: '/company', tone: 'ok' }}
          contacts={{ available: true, contacts: [] }}
        />
      </AppShell>
    )
  }

  if (role === 'fb' && page === 'new-trip-request') {
    const dispatchers: CarrierContact[] = [
      { id: 'c-1', owner_id: profile.id, name: 'Kevin Ortiz', email: 'dispatch@ridgelinehh.com', phone: '(330) 555-0177', phone_ext: '', role: 'dispatcher', user_id: null, invited_at: null, last_used_at: '2026-09-11T00:00:00.000Z', created_at: '2026-09-01T00:00:00.000Z' },
      { id: 'c-2', owner_id: profile.id, name: 'Sam Kowalski', email: 'ops@blueridgetransport.com', phone: '(412) 555-0150', phone_ext: '204', role: 'dispatcher', user_id: null, invited_at: null, last_used_at: null, created_at: '2026-09-02T00:00:00.000Z' },
      { id: 'c-3', owner_id: profile.id, name: 'Anita Shaw', email: 'anita.s@ridgelinehh.com', phone: '(330) 555-0190', phone_ext: '', role: 'dispatcher', user_id: null, invited_at: null, last_used_at: null, created_at: '2026-09-03T00:00:00.000Z' },
    ] as CarrierContact[]
    return (
      <AppShell profile={profile}>
        <main className="mx-auto max-w-2xl px-4 py-8">
          <h1 className="text-2xl font-bold tracking-tight">Create a trip request</h1>
          <p className="mt-1 text-sm text-neutral-600">
            Upload the rate confirmation, invite the dispatcher, and decide how the permits get
            handled — the shared workspace starts as &ldquo;Waiting on Permits&rdquo;.
          </p>
          <BrokerRequestForm slug="summit-freight" defaultPolicy="ask" defaultPayment="ask" dispatchers={dispatchers} />
        </main>
      </AppShell>
    )
  }

  if (role === 'fb' && page === 'dashboard') {
    return (
      <AppShell profile={profile}>
        <BrokerDashboard
          trips={trips}
          warnings={warnings}
          brokerPage={{ id: 'dev-page', owner_id: profile.id, slug: 'summit-freight', company_name: 'Summit Freight Brokerage', created_at: '2026-09-01T00:00:00.000Z' } as unknown as BrokerPage}
          permits={permits}
          drivers={drivers}
          userId={profile.id}
          completions={completions}
          companyStatus={{ label: 'Approved company agent · Summit Freight Brokerage · Broker agent', href: '/company', tone: 'ok' }}
        />
      </AppShell>
    )
  }

  if (page === 'trip' && role === 'ct') {
    const a = DEMO_PILOT_ASSIGNMENTS[0]
    const trip = trips[0]
    const driverProfile: Profile = { ...profile, id: 'dev-preview-driver', email: a.carrierDriver.email, full_name: a.carrierDriver.name, default_role: 'driver' }
    const participants: TripParticipant[] = [
      { id: 'pt-2', trip_id: trip.id, user_id: null, email: a.carrierDispatcher.email, name: a.carrierDispatcher.name, phone: a.carrierDispatcher.phone, phone_ext: null, role: 'dispatcher', status: 'active', invited_by: null, completed_at: null, completion_prompt_dismissed_at: null, share_chat: true, created_at: trip.created_at },
      { id: 'pt-3', trip_id: trip.id, user_id: driverProfile.id, email: driverProfile.email, name: driverProfile.full_name, phone: a.carrierDriver.phone, phone_ext: null, role: 'driver', status: 'active', invited_by: null, completed_at: null, completion_prompt_dismissed_at: null, share_chat: true, created_at: trip.created_at },
    ] as TripParticipant[]
    return (
      <AppShell profile={driverProfile}>
        <DriverView
          trips={trips}
          focusTrip={trip}
          warnings={warnings.filter((w) => w.trip_id === trip.id)}
          permits={permits.filter((p) => p.trip_id === trip.id)}
          userId={driverProfile.id}
          accountCreatedAt={driverProfile.created_at}
          isInternal
          myName={driverProfile.full_name}
          routeRequests={[]}
          units={[]}
          permitUrls={{}}
          chat={[]}
          participants={participants}
          myRole="driver"
          shareChat
          completions={completions}
          routeCredits={{ planName: 'Free', included: 1, used: 0, remaining: 1 }}
          chatLanguages={['en']}
          primaryLanguage="en"
        />
      </AppShell>
    )
  }

  if (page === 'trip' && (role === 'fb' || role === 'cd')) {
    const a = DEMO_PILOT_ASSIGNMENTS[0]
    const trip = trips[0]
    const participants: TripParticipant[] = [
      { id: 'pt-1', trip_id: trip.id, user_id: profile.id, email: profile.email, name: profile.full_name, phone: '(502) 555-0133', phone_ext: null, role: 'broker', status: 'active', invited_by: null, completed_at: null, completion_prompt_dismissed_at: null, share_chat: true, created_at: trip.created_at },
      { id: 'pt-2', trip_id: trip.id, user_id: null, email: a.carrierDispatcher.email, name: a.carrierDispatcher.name, phone: a.carrierDispatcher.phone, phone_ext: null, role: 'dispatcher', status: 'active', invited_by: profile.id, completed_at: null, completion_prompt_dismissed_at: null, share_chat: true, created_at: trip.created_at },
      { id: 'pt-3', trip_id: trip.id, user_id: null, email: a.carrierDriver.email, name: a.carrierDriver.name, phone: a.carrierDriver.phone, phone_ext: null, role: 'driver', status: 'invited', invited_by: profile.id, completed_at: null, completion_prompt_dismissed_at: null, share_chat: true, created_at: trip.created_at },
    ] as TripParticipant[]
    const View = role === 'cd' ? CarrierTripView : BrokerTripView
    return (
      <AppShell profile={profile}>
        <View
          trip={trip}
          myTrips={trips}
          myRole={role === 'cd' ? 'dispatcher' : 'broker'}
          myUserId={profile.id}
          myAccountRole={role === 'cd' ? 'dispatcher' : 'broker'}
          myAccountCreatedAt={profile.created_at}
          participants={participants}
          documents={[]}
          signedUrls={{}}
          permits={permits.filter((p) => p.trip_id === trip.id)}
          warnings={warnings.filter((w) => w.trip_id === trip.id)}
          chat={[]}
          events={[]}
          requests={[]}
          myCompletion={EMPTY_COMPLETION}
          completions={completions}
          shareChat
          routeCredits={{ planName: 'Free', included: 1, used: 0, remaining: 1 }}
          chatLanguages={['en']}
          primaryLanguage="en"
          contacts={{ drivers: [], brokers: [] }}
        />
      </AppShell>
    )
  }

  notFound()
}
