import { SlidersHorizontal, SearchX } from 'lucide-react'
import Link from 'next/link'
import CarplaceSearchForm, { type CarplaceSearchValues } from '@/components/carplace/CarplaceSearchForm'
import VehicleCard from '@/components/carplace/VehicleCard'
import { getCarplaceMessages } from '@/lib/carplace/messages'
import { carplaceHref } from '@/lib/carplace/routes'
import type { VehicleSearchResponse } from '@/lib/carplace/types'
import { carplaceFetchOrDefault } from '@/lib/api'
import { getCarplaceLanguage } from '@/lib/i18n.server'

type RawSearchParams = Record<string, string | string[] | undefined>

export default async function CarplaceSearchPage({ searchParams }: { searchParams?: Promise<RawSearchParams> }) {
  const params = (await searchParams) ?? {}
  const language = await getCarplaceLanguage()
  const copy = getCarplaceMessages(language)
  const value = (key: string) => typeof params[key] === 'string' ? params[key] as string : ''

  const initial: CarplaceSearchValues = {
    pickupLocation: value('pickupLocation') || value('city'),
    dropoffLocation: value('dropoffLocation'),
    dropoffMode: value('dropoffMode') === 'different' ? 'different' : 'same',
    pickupDate: value('pickupDate'),
    pickupTime: value('pickupTime') || '10:00',
    returnDate: value('returnDate'),
    returnTime: value('returnTime') || '10:00',
    driverAge: value('driverAge') || '25',
    promoCode: value('promoCode'),
  }

  const page = Math.max(1, Number(value('page') || '1') || 1)
  const pageSize = 18
  const apiQuery = new URLSearchParams({ page: String(page), pageSize: String(pageSize) })
  if (initial.pickupLocation) { apiQuery.set('city', initial.pickupLocation); apiQuery.set('pickupLocation', initial.pickupLocation) }
  if (initial.dropoffMode) apiQuery.set('dropoffMode', initial.dropoffMode)
  if (initial.dropoffMode === 'different' && initial.dropoffLocation) apiQuery.set('dropoffLocation', initial.dropoffLocation)
  const startDate = toIso(initial.pickupDate, initial.pickupTime)
  const endDate = toIso(initial.returnDate, initial.returnTime)
  if (startDate) apiQuery.set('startDate', startDate)
  if (endDate) apiQuery.set('endDate', endDate)
  for (const key of ['category', 'transmission', 'make', 'model'] as const) if (value(key)) apiQuery.set(key, value(key))
  const maxPriceMad = Number(value('maxPrice'))
  if (Number.isFinite(maxPriceMad) && maxPriceMad > 0) apiQuery.set('maxPrice', String(Math.round(maxPriceMad * 100)))

  const fallback: VehicleSearchResponse = { items: [], pagination: { page, pageSize, totalItems: 0, totalPages: 0 }, facets: { categories: [], transmissions: [], makes: [], price: { min: null, max: null } } }
  const [cities, response] = await Promise.all([
    carplaceFetchOrDefault<string[]>('/carplace/cities', []),
    carplaceFetchOrDefault<VehicleSearchResponse>(`/carplace/search?${apiQuery.toString()}`, fallback),
  ])

  const sort = value('sort') || 'price-asc'
  const items = [...response.items].sort((a, b) => sort === 'price-desc' ? b.dailyRate - a.dailyRate : a.dailyRate - b.dailyRate)
  const cardQuery = buildCardQuery(params)

  return (
    <main className="site-page" id="main-content">
      <section className="border-b border-stone-200 bg-white/85 py-6 dark:border-blue-900 dark:bg-blue-950/80">
        <div className="shell"><CarplaceSearchForm cities={cities} copy={copy} initial={initial} compact /></div>
      </section>

      <div className="shell grid gap-8 py-10 lg:grid-cols-[270px_1fr]">
        <aside className="h-fit rounded-2xl border border-stone-200 bg-white p-5 dark:border-blue-900 dark:bg-blue-950 lg:sticky lg:top-24">
          <h2 className="flex items-center gap-2 text-lg font-black text-blue-950 dark:text-white"><SlidersHorizontal className="h-5 w-5" />{copy.sections.filters}</h2>
          <form action={carplaceHref('/search')} method="get" className="mt-5 grid gap-4">
            {preservedTripInputs(params)}
            <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">{copy.vehicle.category}<select name="category" defaultValue={value('category')} className="carplace-input"><option value="">{copy.results.allCategories}</option>{Object.entries(copy.categories).map(([category, label]) => <option key={category} value={category}>{label}</option>)}</select></label>
            <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">{copy.results.maxPrice}<input type="number" min="0" name="maxPrice" defaultValue={value('maxPrice')} className="carplace-input" inputMode="numeric" /></label>
            <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">{copy.results.transmission}<select name="transmission" defaultValue={value('transmission')} className="carplace-input"><option value="">—</option>{response.facets.transmissions.map((facet) => <option key={facet.value} value={facet.value}>{facet.value} ({facet.count})</option>)}</select></label>
            <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">{copy.results.make}<input name="make" defaultValue={value('make')} className="carplace-input" list="carplace-makes" /><datalist id="carplace-makes">{response.facets.makes.map((facet) => <option key={facet.value} value={facet.value} />)}</datalist></label>
            <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">{copy.results.model}<input name="model" defaultValue={value('model')} className="carplace-input" /></label>
            <button className="carplace-primary-button justify-center" type="submit">{copy.results.apply}</button>
            <Link href={carplaceHref('/search')} className="carplace-secondary-button justify-center">{copy.results.clear}</Link>
          </form>
        </aside>

        <section>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-600 dark:text-orange-400">Carplace</p><h1 className="mt-2 text-3xl font-black tracking-[-0.035em] text-blue-950 dark:text-white">{copy.results.title}</h1><p className="mt-2 text-sm text-stone-500 dark:text-slate-400">{response.pagination.totalItems} {copy.results.count}</p></div>
            <form action={carplaceHref('/search')} method="get" className="flex items-end gap-2">
              {Object.entries(params).flatMap(([key, raw]) => key === 'sort' || key === 'page' ? [] : (Array.isArray(raw) ? raw : [raw]).filter((entry): entry is string => typeof entry === 'string').map((entry) => <input key={`${key}-${entry}`} type="hidden" name={key} value={entry} />))}
              <label className="grid gap-1 text-xs font-bold text-stone-600 dark:text-slate-300">{copy.results.sort}<select name="sort" defaultValue={sort} className="carplace-input"><option value="price-asc">{copy.results.sortPriceAsc}</option><option value="price-desc">{copy.results.sortPriceDesc}</option></select></label>
              <button type="submit" className="carplace-secondary-button">{copy.results.apply}</button>
            </form>
          </div>

          {items.length > 0 ? <div className="mt-7 grid gap-6 md:grid-cols-2 xl:grid-cols-3">{items.map((vehicle) => <VehicleCard key={vehicle.id} vehicle={vehicle} copy={copy} language={language} query={cardQuery} />)}</div> : <div className="mt-8 rounded-[2rem] border border-dashed border-stone-300 p-10 text-center dark:border-blue-800"><SearchX className="mx-auto h-10 w-10 text-stone-400" /><h2 className="mt-4 text-xl font-black text-blue-950 dark:text-white">{copy.results.none}</h2><p className="mt-2 text-sm text-stone-500 dark:text-slate-400">{copy.results.noneBody}</p></div>}

          {response.pagination.totalPages > 1 ? <Pagination current={response.pagination.page} total={response.pagination.totalPages} params={params} previous={copy.results.previous} next={copy.results.next} label={copy.accessibility.pagination} /> : null}
        </section>
      </div>
    </main>
  )
}

function toIso(date?: string, time?: string): string | null { if (!date || !time) return null; const result = new Date(`${date}T${time}:00`); return Number.isNaN(result.getTime()) ? null : result.toISOString() }

function buildCardQuery(params: RawSearchParams): URLSearchParams {
  const query = new URLSearchParams()
  for (const key of ['pickupLocation', 'dropoffLocation', 'dropoffMode', 'pickupDate', 'pickupTime', 'returnDate', 'returnTime', 'driverAge', 'promoCode'] as const) {
    const raw = params[key]
    if (typeof raw === 'string' && raw) query.set(key, raw)
  }
  return query
}

function preservedTripInputs(params: RawSearchParams) {
  return ['pickupLocation', 'dropoffLocation', 'dropoffMode', 'pickupDate', 'pickupTime', 'returnDate', 'returnTime', 'driverAge', 'promoCode'].flatMap((key) => {
    const raw = params[key]
    return (Array.isArray(raw) ? raw : [raw]).filter((entry): entry is string => typeof entry === 'string').map((entry) => <input key={`${key}-${entry}`} type="hidden" name={key} value={entry} />)
  })
}

function Pagination({ current, total, params, previous, next, label }: { current: number; total: number; params: RawSearchParams; previous: string; next: string; label: string }) {
  const href = (page: number) => { const query = new URLSearchParams(); Object.entries(params).forEach(([key, raw]) => { if (key === 'page') return; (Array.isArray(raw) ? raw : [raw]).forEach((entry) => { if (typeof entry === 'string') query.append(key, entry) }) }); query.set('page', String(page)); return `${carplaceHref('/search')}?${query.toString()}` }
  return <nav className="mt-10 flex items-center justify-center gap-3" aria-label={label}>{current > 1 ? <Link href={href(current - 1)} className="carplace-secondary-button">{previous}</Link> : null}<span className="text-sm font-bold text-stone-600 dark:text-slate-300">{current} / {total}</span>{current < total ? <Link href={href(current + 1)} className="carplace-secondary-button">{next}</Link> : null}</nav>
}
