import { ArrowLeft, BadgeCheck, Fuel, Gauge, MapPin, MessageCircle, Phone, ShieldCheck, Star, Users } from 'lucide-react'
import Link from 'next/link'
import { formatCurrency } from '@rentaldrivego/types'
import ProgressiveBookingFlow, { type BookingInitialValues } from '@/components/carplace/ProgressiveBookingFlow'
import VehicleCard from '@/components/carplace/VehicleCard'
import { getCarplaceMessages } from '@/lib/carplace/messages'
import { carplaceCompanyHref, carplaceHref } from '@/lib/carplace/routes'
import type { CompanyBrand, VehicleSearchResponse } from '@/lib/carplace/types'
import { carplaceFetchOrDefault } from '@/lib/api'
import { getCarplaceLanguage } from '@/lib/i18n.server'

interface VehicleDetail {
  id: string
  make: string
  model: string
  year: number
  category: string
  dailyRate: number
  photos: string[]
  seats?: number | null
  transmission?: string | null
  fuelType?: string | null
  features?: string[]
  pickupLocations: string[]
  allowDifferentDropoff: boolean
  dropoffLocations: string[]
  availability?: boolean | null
  availabilityStatus?: 'AVAILABLE' | 'RESERVED' | 'MAINTENANCE' | 'UNAVAILABLE'
  nextAvailableAt?: string | null
  company: { slug: string; name?: string; brand: CompanyBrand | null }
}

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

export default async function CarplaceVehiclePage({ params, searchParams }: { params: Promise<{ slug: string; id: string }>; searchParams?: Promise<RawSearchParams> }) {
  const [resolvedParams, rawParams] = await Promise.all([params, searchParams ?? Promise.resolve({})])
  const { slug, id } = resolvedParams
  const language = await getCarplaceLanguage()
  const copy = getCarplaceMessages(language)
  const vehicle = await carplaceFetchOrDefault<VehicleDetail | null>(`/carplace/${encodeURIComponent(slug)}/vehicles/${encodeURIComponent(id)}`, null)

  if (!vehicle) {
    return <main className="site-page"><div className="shell py-20"><section className="mx-auto max-w-2xl rounded-[2rem] border border-stone-200 bg-white p-8 text-center dark:border-blue-900 dark:bg-blue-950"><h1 className="text-3xl font-black text-blue-950 dark:text-white">{copy.status.unavailable}</h1><p className="mt-3 text-stone-600 dark:text-slate-300">{copy.status.unavailableBody}</p><Link href={carplaceHref()} className="carplace-primary-button mt-7 justify-center">{copy.actions.back}</Link></section></div></main>
  }

  const companyName = vehicle.company.brand?.displayName || vehicle.company.name || copy.vehicle.company
  const companySlug = vehicle.company.brand?.subdomain || vehicle.company.slug || slug
  const first = vehicle.photos?.[0]
  const rest = vehicle.photos?.slice(1, 5) ?? []
  const related = await carplaceFetchOrDefault<VehicleSearchResponse>(`/carplace/search?category=${encodeURIComponent(vehicle.category)}&pageSize=4`, { items: [], pagination: { page: 1, pageSize: 4, totalItems: 0, totalPages: 0 }, facets: { categories: [], transmissions: [], makes: [], price: { min: null, max: null } } })
  const similar = related.items.filter((item) => item.id !== vehicle.id).slice(0, 3)
  const initial = buildInitial(rawParams)
  const preserveQuery = buildPreserveQuery(rawParams)

  return (
    <main className="site-page" id="main-content">
      <div className="shell py-8 sm:py-12">
        <nav className="flex flex-wrap items-center gap-2 text-sm text-stone-500 dark:text-slate-400">
          <Link href={carplaceHref()} className="no-underline hover:text-orange-600">Carplace</Link><span>/</span>
          <Link href={carplaceCompanyHref(companySlug)} className="no-underline hover:text-orange-600">{companyName}</Link><span>/</span>
          <span className="font-semibold text-blue-950 dark:text-white">{vehicle.make} {vehicle.model}</span>
        </nav>

        <div className="mt-7 grid gap-8 lg:grid-cols-[minmax(0,1fr)_410px]">
          <div className="min-w-0 space-y-7">
            <section className="grid gap-3 sm:grid-cols-[2fr_1fr]">
              <div className="aspect-[16/10] overflow-hidden rounded-[2rem] bg-gradient-to-br from-blue-100 to-stone-100 dark:from-blue-900 dark:to-blue-950 sm:row-span-2">
                {first ? <img src={first} alt={`${vehicle.year} ${vehicle.make} ${vehicle.model}`} className="h-full w-full object-cover" /> : <div className="flex h-full items-center justify-center text-sm font-semibold text-stone-500 dark:text-slate-400">{copy.vehicle.noPhoto}</div>}
              </div>
              {rest.slice(0, 2).map((photo, index) => <div key={`${photo}-${index}`} className="aspect-[16/10] overflow-hidden rounded-2xl bg-stone-100 dark:bg-blue-900"><img src={photo} alt={`${vehicle.make} ${vehicle.model} ${index + 2}`} className="h-full w-full object-cover" /></div>)}
            </section>

            <section className="rounded-[2rem] border border-stone-200 bg-white p-6 dark:border-blue-900 dark:bg-blue-950 sm:p-8">
              <div className="flex flex-col gap-5 sm:flex-row sm:items-start sm:justify-between">
                <div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-600 dark:text-orange-400">{copy.categories[vehicle.category as keyof typeof copy.categories] ?? vehicle.category}</p><h1 className="mt-2 text-3xl font-black tracking-[-0.04em] text-blue-950 dark:text-white sm:text-4xl">{vehicle.make} {vehicle.model}</h1><p className="mt-2 text-stone-500 dark:text-slate-400">{vehicle.year}</p></div>
                <div className="text-start sm:text-end"><p className="text-xs text-stone-500 dark:text-slate-400">{copy.vehicle.from}</p><p className="text-2xl font-black text-blue-950 dark:text-white">{formatCurrency(vehicle.dailyRate, 'MAD', language)} <span className="text-sm font-semibold text-stone-500 dark:text-slate-400">{copy.vehicle.perDay}</span></p></div>
              </div>

              <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                <Spec icon={Gauge} label={copy.vehicle.transmission} value={vehicle.transmission} />
                <Spec icon={Users} label={copy.vehicle.seats} value={vehicle.seats ? String(vehicle.seats) : null} />
                <Spec icon={Fuel} label={copy.vehicle.fuel} value={vehicle.fuelType} />
                <Spec icon={ShieldCheck} label={copy.vehicle.category} value={copy.categories[vehicle.category as keyof typeof copy.categories] ?? vehicle.category} />
              </div>

              {vehicle.features && vehicle.features.length > 0 ? <div className="mt-7 border-t border-stone-200 pt-6 dark:border-blue-900"><h2 className="text-sm font-black text-blue-950 dark:text-white">{copy.vehicle.features}</h2><div className="mt-3 flex flex-wrap gap-2">{vehicle.features.map((feature) => <span key={feature} className="carplace-spec">{feature}</span>)}</div></div> : null}
            </section>

            <section className="grid gap-5 md:grid-cols-2">
              <div className="rounded-[2rem] border border-stone-200 bg-white p-6 dark:border-blue-900 dark:bg-blue-950"><h2 className="flex items-center gap-2 text-lg font-black text-blue-950 dark:text-white"><MapPin className="h-5 w-5 text-orange-600" />{copy.vehicle.pickupLocations}</h2><div className="mt-4 flex flex-wrap gap-2">{vehicle.pickupLocations.length > 0 ? vehicle.pickupLocations.map((location) => <span key={location} className="carplace-spec">{location}</span>) : <span className="text-sm text-stone-500 dark:text-slate-400">{vehicle.company.brand?.publicCity || '—'}</span>}</div></div>
              <div className="rounded-[2rem] border border-stone-200 bg-white p-6 dark:border-blue-900 dark:bg-blue-950"><h2 className="flex items-center gap-2 text-lg font-black text-blue-950 dark:text-white"><BadgeCheck className="h-5 w-5 text-emerald-600" />{companyName}</h2><div className="mt-4 flex flex-wrap gap-2">{vehicle.company.brand?.carplaceRating ? <span className="carplace-spec"><Star className="h-4 w-4 fill-current text-amber-500" />{vehicle.company.brand.carplaceRating.toFixed(1)}</span> : <span className="carplace-spec">{copy.vehicle.new}</span>}{vehicle.company.brand?.publicCity ? <span className="carplace-spec"><MapPin className="h-4 w-4" />{vehicle.company.brand.publicCity}</span> : null}</div><Link href={`${carplaceCompanyHref(companySlug)}${preserveQuery ? `?${preserveQuery}` : ''}`} className="carplace-secondary-button mt-5">{copy.actions.viewFleet}<ArrowLeft className="h-4 w-4 rotate-180 rtl:rotate-0" /></Link></div>
            </section>

            {(vehicle.company.brand?.publicPhone || vehicle.company.brand?.whatsappNumber) ? <section className="rounded-[2rem] border border-stone-200 bg-white p-6 dark:border-blue-900 dark:bg-blue-950"><h2 className="text-lg font-black text-blue-950 dark:text-white">{copy.vehicle.directContact}</h2><p className="mt-2 text-sm text-stone-500 dark:text-slate-400">{companyName}</p><div className="mt-5 flex flex-wrap gap-3">{vehicle.company.brand.publicPhone ? <a className="carplace-secondary-button" href={`tel:${vehicle.company.brand.publicPhone}`}><Phone className="h-4 w-4" />{copy.vehicle.phone}</a> : null}{vehicle.company.brand.whatsappNumber ? <a className="carplace-primary-button" href={`https://wa.me/${vehicle.company.brand.whatsappNumber.replace(/\D/g, '')}`} target="_blank" rel="noreferrer"><MessageCircle className="h-4 w-4" />{copy.vehicle.whatsapp}</a> : null}</div></section> : null}
          </div>

          <aside className="h-fit lg:sticky lg:top-24">
            <ProgressiveBookingFlow vehicleId={vehicle.id} companySlug={companySlug} vehicleName={`${vehicle.year} ${vehicle.make} ${vehicle.model}`} companyName={companyName} dailyRate={vehicle.dailyRate} pickupLocations={vehicle.pickupLocations} allowDifferentDropoff={vehicle.allowDifferentDropoff} dropoffLocations={vehicle.dropoffLocations} language={language} copy={copy} initial={initial} />
          </aside>
        </div>

        {similar.length > 0 ? <section className="mt-16"><h2 className="text-3xl font-black tracking-[-0.035em] text-blue-950 dark:text-white">{copy.vehicle.similar}</h2><div className="mt-6 grid gap-6 md:grid-cols-2 xl:grid-cols-3">{similar.map((item) => <VehicleCard key={item.id} vehicle={item} copy={copy} language={language} query={preserveQuery} />)}</div></section> : null}
      </div>
    </main>
  )
}

function Spec({ icon: Icon, label, value }: { icon: typeof Gauge; label: string; value?: string | null }) { if (!value) return null; return <div className="rounded-2xl bg-stone-50 p-4 dark:bg-blue-900/30"><Icon className="h-5 w-5 text-orange-600 dark:text-orange-400" /><p className="mt-3 text-xs font-semibold text-stone-500 dark:text-slate-400">{label}</p><p className="mt-1 font-black text-blue-950 dark:text-white">{value}</p></div> }

function buildInitial(params: RawSearchParams): BookingInitialValues { const v = (key: string) => typeof params[key] === 'string' ? params[key] as string : undefined; return { pickupLocation: v('pickupLocation'), dropoffLocation: v('dropoffLocation'), pickupDate: v('pickupDate'), pickupTime: v('pickupTime'), returnDate: v('returnDate'), returnTime: v('returnTime'), promoCode: v('promoCode'), driverAge: v('driverAge') } }
function buildPreserveQuery(params: RawSearchParams): string { const query = new URLSearchParams(); for (const key of ['pickupLocation', 'dropoffLocation', 'dropoffMode', 'pickupDate', 'pickupTime', 'returnDate', 'returnTime', 'driverAge', 'promoCode']) { const raw = params[key]; if (typeof raw === 'string' && raw) query.set(key, raw) } return query.toString() }
