'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { cityState, formatFullDate } from '@/lib/format'

/**
 * Per-trip context chooser (decision D13, 2026-09-30). A person who holds
 * several contexts matching the role they were placed with picks the company
 * and role they join THIS trip with. Shown instead of the workspace; the
 * summary is the dashboard's fields only (A8) — documents, permits and chat
 * stay behind the choice (§16).
 */
export interface TripContextChooserProps {
  tripId: string
  tripRef: string
  summary: {
    origin: string
    destination: string
    pickup_date: string | null
    delivery_date: string | null
    carrier_name: string | null
    broker_name: string | null
  }
  choices: { key: string; label: string; role_type: string; company_id: string | null; company_name: string | null }[]
}

export function TripContextChooser({ tripId, tripRef, summary, choices }: TripContextChooserProps) {
  const router = useRouter()
  const [selected, setSelected] = useState<string>(choices[0]?.key ?? '')
  const [pending, setPending] = useState(false)
  const chosen = choices.find((c) => c.key === selected) ?? null
  const route = [cityState(summary.origin) || summary.origin, cityState(summary.destination) || summary.destination].filter(Boolean).join(' → ')
  // Date-only strings are shown as calendar dates, not shifted by the viewer's timezone (same as the trip header).
  const day = (v: string) => formatFullDate(/^\d{4}-\d{2}-\d{2}$/.test(v) ? `${v}T12:00:00` : v)
  const dates = [summary.pickup_date, summary.delivery_date].some(Boolean)
    ? `${summary.pickup_date ? day(summary.pickup_date) : '—'} → ${summary.delivery_date ? day(summary.delivery_date) : '—'}`
    : '—'

  async function submit() {
    if (!chosen) return
    setPending(true)
    try {
      const res = await fetch(`/api/trips/${tripId}/context`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ context_key: chosen.key }),
      })
      const body = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(body.error || 'Could not save your choice.')
        return
      }
      router.refresh()
    } finally {
      setPending(false)
    }
  }

  return (
    <div className="mx-auto flex min-h-[60vh] max-w-xl items-center px-4 py-10">
      <Card className="w-full">
        <CardHeader>
          <CardTitle>Which workspace are you joining Trip {tripRef} with?</CardTitle>
          <CardDescription>You act with one company and role on each trip. This choice applies to this trip only.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-5">
          <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
            <dt className="text-neutral-500">Route</dt>
            <dd className="font-medium">{route || '—'}</dd>
            <dt className="text-neutral-500">Dates</dt>
            <dd className="font-medium">{dates}</dd>
            <dt className="text-neutral-500">Carrier</dt>
            <dd className="font-medium">{summary.carrier_name || '—'}</dd>
            <dt className="text-neutral-500">Broker</dt>
            <dd className="font-medium">{summary.broker_name || '—'}</dd>
          </dl>
          <div role="radiogroup" aria-label="Workspace" className="space-y-2">
            {choices.map((c) => (
              <label
                key={c.key}
                className={`flex cursor-pointer items-center gap-3 rounded-xl border p-3 text-sm ${selected === c.key ? 'border-neutral-900 bg-neutral-50' : 'border-neutral-200 hover:bg-neutral-50'}`}
              >
                <input
                  type="radio"
                  name="trip-context"
                  value={c.key}
                  checked={selected === c.key}
                  onChange={() => setSelected(c.key)}
                  className="h-4 w-4"
                />
                <span className="font-medium">{c.label}</span>
              </label>
            ))}
          </div>
          <Button type="button" className="w-full" disabled={!chosen || pending} onClick={submit}>
            {pending ? 'Saving…' : `Continue as ${chosen?.label ?? '…'}`}
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
