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

interface Vehicle {
  id: string
  make: string
  model: string
  year: number
  category: string
  dailyRate: number
  seats: number
  transmission: string
  fuelType: string
  photos: string[]
}

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

interface PageProps {
  searchParams?: {
    category?: string
    maxPrice?: string
    transmission?: string
  }
}

export const dynamic = 'force-dynamic'

export default async function VehiclesPage({ searchParams = {} }: PageProps) {
  const slug = DEFAULT_COMPANY_SLUG
  const language = getPublicSiteLanguage()
  const dict = getPublicSiteDictionary(language)
  const [vehicles, brand] = await Promise.all([
    siteFetchOrDefault<Vehicle[]>(`/site/${slug}/vehicles`, []),
    siteFetchOrDefault<BrandResponse | null>(`/site/${slug}/brand`, null),
  ])
  const pageSections = resolvePageSectionsConfig(brand?.brand?.menuConfig)

  const categories = Array.from(new Set(vehicles.map((v) => v.category))).sort()
  const transmissions = Array.from(new Set(vehicles.map((v) => v.transmission))).sort()
  const maxPossiblePrice = vehicles.reduce((max, v) => Math.max(max, v.dailyRate), 0)

  const filtered = vehicles.filter((v) => {
    if (searchParams.category && v.category !== searchParams.category) return false
    if (searchParams.transmission && v.transmission !== searchParams.transmission) return false
    if (searchParams.maxPrice && v.dailyRate > Number(searchParams.maxPrice)) return false
    return true
  })

  return (
    <main className="min-h-screen bg-slate-50 py-10">
      <div className="shell">
        {pageSections.vehicles.header ? <div className="mb-8">
          <h1 className="text-4xl font-black text-slate-900">{dict.vehicles.title}</h1>
          <p className="mt-2 text-slate-500">
            {dict.vehicles.available(filtered.length)}
          </p>
        </div> : null}

        <div className={`grid gap-8 ${pageSections.vehicles.filters ? 'lg:grid-cols-[260px_1fr]' : ''}`}>
          {pageSections.vehicles.filters ? (
            <aside>
              <VehicleFilters
                language={language}
                categories={categories}
                transmissions={transmissions}
                maxPossiblePrice={maxPossiblePrice}
                current={{
                  category: searchParams.category ?? '',
                  transmission: searchParams.transmission ?? '',
                  maxPrice: searchParams.maxPrice ?? '',
                }}
              />
            </aside>
          ) : null}

          {pageSections.vehicles.grid ? <section>
            {filtered.length === 0 ? (
              <div className="card p-10 text-center">
                <p className="text-lg font-semibold text-slate-700">{dict.vehicles.noVehiclesTitle}</p>
                <p className="mt-2 text-sm text-slate-500">{dict.vehicles.noVehiclesBody}</p>
                <Link
                  href="/vehicles"
                  className="mt-6 inline-block rounded-full bg-slate-900 px-6 py-3 text-sm font-semibold text-white"
                >
                  {dict.vehicles.clearFilters}
                </Link>
              </div>
            ) : (
              <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
                {filtered.map((vehicle) => (
                  <article key={vehicle.id} className="card overflow-hidden flex flex-col">
                    <div className="aspect-[16/10] bg-slate-100">
                      {vehicle.photos[0] ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={vehicle.photos[0]}
                          alt={`${vehicle.make} ${vehicle.model}`}
                          className="h-full w-full object-cover"
                        />
                      ) : (
                        <div className="flex h-full items-center justify-center text-sm text-slate-400">
                          {dict.vehicles.noPhoto}
                        </div>
                      )}
                    </div>
                    <div className="flex flex-1 flex-col p-5">
                      <h2 className="text-xl font-bold text-slate-900">
                        {vehicle.make} {vehicle.model}
                      </h2>
                      <p className="mt-1 text-sm text-slate-500">{vehicle.category}</p>

                      <div className="mt-3 flex flex-wrap gap-2 text-xs text-slate-600">
                        <span className="rounded-full bg-slate-100 px-3 py-1">{vehicle.transmission}</span>
                        <span className="rounded-full bg-slate-100 px-3 py-1">{dict.vehicles.seats(vehicle.seats)}</span>
                        <span className="rounded-full bg-slate-100 px-3 py-1">{vehicle.fuelType}</span>
                      </div>

                      <div className="mt-auto pt-4 flex items-end justify-between">
                        <div>
                          <p className="text-xl font-black text-slate-900">
                            {formatCurrency(vehicle.dailyRate, 'MAD')}
                          </p>
                          <p className="text-xs text-slate-500">{dict.vehicles.perDay}</p>
                        </div>
                        <Link
                          href={`/vehicles/${vehicle.id}`}
                          className="rounded-full bg-slate-900 px-5 py-2.5 text-sm font-semibold text-white hover:bg-slate-700 transition-colors"
                        >
                          {dict.vehicles.viewDetails}
                        </Link>
                      </div>
                    </div>
                  </article>
                ))}
              </div>
            )}
          </section> : null}
        </div>
      </div>
    </main>
  )
}
