import { redirect } from 'next/navigation'
import Link from 'next/link'
import { getProfile, getSessionUser } from '@/lib/auth'
import { createAdminClient } from '@/lib/supabase/admin'
import { getVisibleTripIds, getTripCompletions } from '@/lib/data/trips'
import { inChunks } from '@/lib/data/chunked'
import { resolveStatusForUser } from '@/lib/domain/status'
import { AppShell } from '@/components/app/app-shell'
import { StatusBadge } from '@/components/app/status-badge'
import { formatFullDate } from '@/lib/format'
import type { Trip } from '@/types/db'

/** Searchable completed-trip history — filter by carrier, commodity, lane, ref. */
export default async function HistoryPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>
}) {
  const user = await getSessionUser()
  if (!user) redirect('/login')
  const profile = (await getProfile())!
  const { q } = await searchParams
  const query = (q ?? '').trim()

  const visibleIds = await getVisibleTripIds(user)
  // History is personal too (2026-09-07): a trip THIS user marked complete
  // belongs in their history even while it is still active for everyone else.
  const completions = await getTripCompletions(user, visibleIds)
  const myCompletedIds = visibleIds.filter((id) => completions[id]?.completedAt)

  const admin = createAdminClient()

  // Which trips belong in THIS user's history: finished trip-wide, or finished
  // by them personally. Resolved as an explicit id list rather than stacking a
  // second .or() on top of the text search, so the two filters cannot interact.
  // Chunked (2026-09-11): an admin sees every trip on the platform, and a
  // single `.in()` over thousands of ids overflows the request URL.
  const { data: statusRows } = await inChunks<{ id: string; status: string }>(visibleIds, (chunk) =>
    admin.from('trips').select('id, status').in('id', chunk),
  )
  const personallyCompleted = new Set(myCompletedIds)
  const historyIds = statusRows
    .filter((t) => ['completed', 'cancelled'].includes(t.status) || personallyCompleted.has(t.id))
    .map((t) => t.id)

  const like = `%${query}%`
  const { data: found } = await inChunks<Trip>(historyIds, (chunk) => {
    let request = admin.from('trips').select('*').in('id', chunk)
    if (query) {
      request = request.or(
        `carrier_name.ilike.${like},commodity.ilike.${like},origin.ilike.${like},destination.ilike.${like},ref_code.ilike.${like}`,
      )
    }
    return request
  })
  // Newest completion first, then most recently updated — chunks arrive in
  // arbitrary order, so the ordering is applied here.
  const trips = found.sort(
    (a, b) =>
      (b.completed_at ?? '').localeCompare(a.completed_at ?? '') ||
      b.updated_at.localeCompare(a.updated_at),
  )

  return (
    <AppShell profile={profile}>
      <main className="mx-auto max-w-4xl px-4 py-8">
        <h1 className="text-2xl font-bold tracking-tight">Trip history</h1>
        <p className="mt-1 text-sm text-neutral-600">
          Completed and cancelled trips stay searchable — find them by carrier, commodity, lane, or
          reference.
        </p>

        <form className="mt-5 flex gap-2" action="/history">
          <input
            name="q"
            defaultValue={query}
            placeholder="Search by carrier, commodity, city, or ref code…"
            className="flex-1 rounded-lg border bg-white px-3.5 py-2.5 text-sm outline-none focus:border-neutral-500"
          />
          <button className="rounded-lg bg-neutral-900 px-4 py-2.5 text-sm font-semibold text-white">
            Search
          </button>
        </form>

        <div className="mt-6 space-y-2">
          {trips.length === 0 && (
            <p className="rounded-xl border border-dashed p-10 text-center text-sm text-neutral-500">
              {query ? `No completed trips match “${query}”.` : 'No completed trips yet.'}
            </p>
          )}
          {trips.map((t) => (
            <Link
              key={t.id}
              href={`/trips/${t.id}`}
              className="flex flex-wrap items-center justify-between gap-2 rounded-xl border bg-white p-4 transition hover:border-neutral-400"
            >
              <div className="min-w-0">
                <p className="truncate font-semibold">
                  {t.origin} → {t.destination}
                </p>
                <p className="mt-0.5 text-sm text-neutral-500">
                  {t.commodity} · {t.carrier_name || '—'} ·{' '}
                  <span className="font-mono text-xs">{t.ref_code}</span>
                </p>
              </div>
              <div className="flex items-center gap-3">
                <span className="text-sm text-neutral-500">
                  {formatFullDate(t.completed_at ?? t.updated_at)}
                </span>
                <StatusBadge
                  status={resolveStatusForUser(t.status, completions[t.id])}
                  policy={t.permit_policy}
                />
              </div>
            </Link>
          ))}
        </div>
      </main>
    </AppShell>
  )
}
