import Link from 'next/link'
import { DEFAULT_COMPANY_SLUG, siteFetchOrDefault } from '@/lib/api'
import { formatCurrency } from '@rentaldrivego/types'
import { getPublicSiteDictionary } from '@/lib/i18n'
import { getPublicSiteLanguage } from '@/lib/i18n.server'
import type { PublicSitePageSections } from '@rentaldrivego/types'
import { resolvePageSectionsConfig } from '@/lib/pageSections'

interface VehicleDetail {
  id: string
  make: string
  model: string
  year: number
  category: string
  dailyRate: number
  seats: number
  transmission: string
  fuelType: string
  features: string[]
  photos: string[]
  availability: boolean
  availabilityStatus: 'AVAILABLE' | 'RESERVED' | 'MAINTENANCE' | 'UNAVAILABLE'
  nextAvailableAt: string | null
}

interface BrandResponse {
  brand: {
    menuConfig?: {
      pageSections?: Partial<PublicSitePageSections> | null
    } | null
  } | null
}

export default async function VehiclePage({ params }: { params: { id: string } }) {
  const dict = getPublicSiteDictionary(getPublicSiteLanguage())
  const [vehicle, brand] = await Promise.all([
    siteFetchOrDefault<VehicleDetail | null>(`/site/${DEFAULT_COMPANY_SLUG}/vehicles/${params.id}`, null),
    siteFetchOrDefault<BrandResponse | null>(`/site/${DEFAULT_COMPANY_SLUG}/brand`, null),
  ])
  const pageSections = resolvePageSectionsConfig(brand?.brand?.menuConfig)

  if (!vehicle) {
    return (
      <main className="min-h-screen bg-slate-50 py-10">
        <div className="shell">
          <section className="card p-8">
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-sky-700">{dict.vehicles.unavailable.eyebrow}</p>
            <h1 className="mt-3 text-3xl font-black text-slate-900">{dict.vehicles.unavailable.title}</h1>
            <p className="mt-3 text-slate-600">{dict.vehicles.unavailable.body}</p>
            <div className="mt-6">
              <Link href="/" className="rounded-full bg-slate-900 px-6 py-3 text-sm font-semibold text-white">{dict.vehicles.unavailable.backHome}</Link>
            </div>
          </section>
        </div>
      </main>
    )
  }

  const availabilityDate = vehicle.nextAvailableAt
    ? new Date(vehicle.nextAvailableAt).toLocaleDateString('en-GB', { year: 'numeric', month: 'long', day: 'numeric' })
    : null

  return (
    <main className="min-h-screen bg-slate-50 py-10">
      <div className={`shell grid gap-8 ${pageSections.vehicleDetail.gallery && pageSections.vehicleDetail.summary ? 'lg:grid-cols-[1.2fr_0.8fr]' : ''}`}>
        {pageSections.vehicleDetail.gallery ? <section className="grid gap-4 sm:grid-cols-2">
          {vehicle.photos.map((photo, index) => (
            <div key={`${photo}-${index}`} className="card overflow-hidden">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={photo} alt={`${vehicle.make} ${vehicle.model} ${index + 1}`} className="h-full w-full object-cover" />
            </div>
          ))}
        </section> : null}
        {pageSections.vehicleDetail.summary ? <aside className="card p-6 h-fit">
          <h1 className="text-4xl font-black text-slate-900">{vehicle.make} {vehicle.model}</h1>
          <p className="mt-3 text-slate-600">{vehicle.year} · {vehicle.category} · {vehicle.transmission}</p>
          <p className="mt-6 text-3xl font-black text-slate-900">{formatCurrency(vehicle.dailyRate, 'MAD')}<span className="text-base font-medium text-slate-500"> {dict.vehicles.detail.perDay}</span></p>
          {!vehicle.availability && (
            <div className="mt-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
              {availabilityDate ? `${dict.vehicles.detail.availableFrom} ${availabilityDate}` : dict.vehicles.detail.unavailableNoDate}
            </div>
          )}
          <div className="mt-6 flex flex-wrap gap-2">
            {vehicle.features.map((feature) => (
              <span key={feature} className="rounded-full bg-slate-100 px-3 py-1 text-xs font-medium text-slate-700">{feature}</span>
            ))}
          </div>
          <div className="mt-8 flex gap-3">
            <Link href={`/book?vehicleId=${vehicle.id}`} className="rounded-full bg-slate-900 px-6 py-3 text-sm font-semibold text-white">{dict.vehicles.detail.bookNow}</Link>
            <Link href="/" className="rounded-full border border-slate-300 px-6 py-3 text-sm font-semibold text-slate-700">{dict.vehicles.detail.back}</Link>
          </div>
        </aside> : null}
      </div>
    </main>
  )
}
