import { ArrowRight, BadgeCheck, Building2, CalendarCheck2, CarFront, CircleDollarSign, FileCheck2, MapPin, SearchCheck, ShieldCheck, Sparkles } from 'lucide-react'
import Link from 'next/link'
import CarplaceSearchForm from '@/components/carplace/CarplaceSearchForm'
import VehicleCard from '@/components/carplace/VehicleCard'
import { getCarplaceMessages } from '@/lib/carplace/messages'
import { formatOfferValue } from '@/lib/carplace/offers'
import { carplaceCompanyHref, carplaceHref } from '@/lib/carplace/routes'
import type { CarplaceHomeResponse } from '@/lib/carplace/types'
import { carplaceFetchOrDefault } from '@/lib/api'
import { getCarplaceLanguage } from '@/lib/i18n.server'

const CATEGORY_ICONS = {
  ECONOMY: CircleDollarSign,
  COMPACT: CarFront,
  MIDSIZE: CarFront,
  FULLSIZE: CarFront,
  SUV: ShieldCheck,
  LUXURY: Sparkles,
  VAN: Building2,
  TRUCK: Building2,
} as const

export default async function CarplaceHomePage({ searchParams }: { searchParams?: Promise<Record<string, string | string[] | undefined>> }) {
  const language = await getCarplaceLanguage()
  const copy = getCarplaceMessages(language)
  const fallback: CarplaceHomeResponse = { cities: [], offers: [], vehicles: [], companies: [] }
  const home = await carplaceFetchOrDefault<CarplaceHomeResponse>('/carplace/home', fallback)

  return (
    <main className="site-page" id="main-content">
      <section className="carplace-hero site-glow">
        <div className="shell grid gap-10 py-12 lg:grid-cols-[1.05fr_.95fr] lg:items-center lg:py-20">
          <div className="max-w-3xl">
            <p className="site-kicker">{copy.hero.eyebrow}</p>
            <h1 className="mt-5 text-4xl font-black leading-[1.03] tracking-[-0.045em] text-blue-950 dark:text-white sm:text-6xl">{copy.hero.title}</h1>
            <p className="mt-6 max-w-2xl text-base leading-8 text-stone-600 dark:text-slate-300 sm:text-lg">{copy.hero.body}</p>
            <div className="mt-8 flex flex-wrap gap-3 text-sm font-semibold text-stone-700 dark:text-slate-200">
              <span className="carplace-trust-pill"><BadgeCheck className="h-4 w-4 text-emerald-600" />{copy.trust[0][0]}</span>
              <span className="carplace-trust-pill"><CalendarCheck2 className="h-4 w-4 text-blue-700 dark:text-blue-300" />{copy.trust[1][0]}</span>
              <span className="carplace-trust-pill"><FileCheck2 className="h-4 w-4 text-orange-600" />{copy.trust[2][0]}</span>
            </div>
          </div>

          <div className="relative">
            <div className="absolute -inset-5 -z-10 rounded-[3rem] bg-gradient-to-br from-orange-300/30 via-transparent to-blue-400/25 blur-2xl" />
            <CarplaceSearchForm cities={home.cities} copy={copy} />
          </div>
        </div>
      </section>

      <section className="border-y border-stone-200 bg-white/80 dark:border-blue-900 dark:bg-blue-950/70">
        <div className="shell grid gap-px py-6 sm:grid-cols-2 lg:grid-cols-4">
          {copy.trust.map(([title, body], index) => {
            const Icon = [Building2, SearchCheck, BadgeCheck, CircleDollarSign][index] ?? ShieldCheck
            return <div key={title} className="flex gap-3 px-4 py-4"><span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-blue-50 text-blue-800 dark:bg-blue-900/50 dark:text-blue-200"><Icon className="h-5 w-5" /></span><div><h2 className="text-sm font-black text-blue-950 dark:text-white">{title}</h2><p className="mt-1 text-xs leading-5 text-stone-500 dark:text-slate-400">{body}</p></div></div>
          })}
        </div>
      </section>

      <section className="site-section">
        <SectionHeading eyebrow="Carplace" title={copy.sections.cities} />
        <div className="mt-6 flex flex-wrap gap-3">
          {home.cities.length > 0 ? home.cities.slice(0, 16).map((city) => (
            <Link key={city} href={`${carplaceHref('/search')}?pickupLocation=${encodeURIComponent(city)}`} className="carplace-city-link"><MapPin className="h-4 w-4" />{city}</Link>
          )) : <p className="text-sm text-stone-500 dark:text-slate-400">{copy.status.unavailableBody}</p>}
        </div>
      </section>

      <section className="site-section pt-0">
        <SectionHeading eyebrow="Carplace" title={copy.sections.categories} />
        <div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {Object.entries(copy.categories).map(([value, label]) => {
            const Icon = CATEGORY_ICONS[value as keyof typeof CATEGORY_ICONS] ?? CarFront
            return (
              <Link key={value} href={`${carplaceHref('/search')}?category=${value}`} className="carplace-category-card">
                <span className="grid h-12 w-12 place-items-center rounded-2xl bg-blue-50 text-blue-900 dark:bg-blue-900/50 dark:text-blue-100"><Icon className="h-6 w-6" /></span>
                <span className="mt-5 flex items-center justify-between gap-3 text-lg font-black text-blue-950 dark:text-white">{label}<ArrowRight className="h-4 w-4 rtl:rotate-180" /></span>
              </Link>
            )
          })}
        </div>
      </section>

      {home.offers.length > 0 ? (
        <section id="offers" className="site-section scroll-mt-24">
          <SectionHeading eyebrow={copy.nav.deals} title={copy.sections.offers} />
          <div className="mt-6 grid gap-5 md:grid-cols-2 lg:grid-cols-3">
            {home.offers.slice(0, 6).map((offer) => {
              const slug = offer.company.brand?.subdomain || offer.company.slug || ''
              return (
                <article key={offer.id} className="carplace-offer-card">
                  <div className="flex items-start justify-between gap-4"><div><p className="text-xs font-bold uppercase tracking-[0.16em] text-orange-200">{offer.company.brand?.displayName ?? copy.vehicle.company}</p><h3 className="mt-2 text-xl font-black text-white">{offer.title}</h3></div><span className="rounded-2xl bg-white px-3 py-2 text-2xl font-black text-blue-950">{formatOfferValue(offer, language)}</span></div>
                  <p className="mt-6 text-sm text-blue-100">{new Intl.DateTimeFormat(language === 'ar' ? 'ar-MA' : language === 'fr' ? 'fr-MA' : 'en-MA', { dateStyle: 'medium' }).format(new Date(offer.validUntil))}</p>
                  {slug ? <Link href={carplaceCompanyHref(slug)} className="mt-5 inline-flex items-center gap-2 text-sm font-bold text-white no-underline">{copy.actions.viewFleet}<ArrowRight className="h-4 w-4 rtl:rotate-180" /></Link> : null}
                </article>
              )
            })}
          </div>
        </section>
      ) : null}

      <section className="site-section">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
          <SectionHeading eyebrow="Carplace" title={copy.sections.vehicles} />
          <Link href={carplaceHref('/search')} className="carplace-secondary-button">{copy.actions.search}<ArrowRight className="h-4 w-4 rtl:rotate-180" /></Link>
        </div>
        {home.vehicles.length > 0 ? <div className="mt-6 grid gap-6 md:grid-cols-2 xl:grid-cols-3">{home.vehicles.slice(0, 9).map((vehicle) => <VehicleCard key={vehicle.id} vehicle={vehicle} copy={copy} language={language} />)}</div> : <EmptyState copy={copy.status.unavailableBody} />}
      </section>

      <section id="companies" className="site-section scroll-mt-24">
        <SectionHeading eyebrow={copy.nav.companies} title={copy.sections.companies} />
        {home.companies.length > 0 ? (
          <div className="mt-6 grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
            {home.companies.slice(0, 8).map((company) => {
              const slug = company.brand?.subdomain || company.slug || ''
              return (
                <Link key={company.id} href={carplaceCompanyHref(slug)} className="carplace-company-card">
                  <div className="flex items-start justify-between gap-3"><span className="grid h-12 w-12 place-items-center rounded-2xl bg-blue-50 text-blue-900 dark:bg-blue-900/50 dark:text-blue-100"><Building2 className="h-6 w-6" /></span>{company.brand?.carplaceRating ? <span className="rounded-full bg-amber-50 px-2.5 py-1 text-xs font-bold text-amber-800 dark:bg-amber-950/50 dark:text-amber-200">★ {company.brand.carplaceRating.toFixed(1)}</span> : null}</div>
                  <h3 className="mt-5 truncate text-lg font-black text-blue-950 dark:text-white">{company.brand?.displayName || company.name || copy.vehicle.company}</h3>
                  <p className="mt-2 flex items-center gap-2 text-sm text-stone-500 dark:text-slate-400"><MapPin className="h-4 w-4" />{company.brand?.publicCity || copy.company.partner}</p>
                  <p className="mt-4 text-sm font-semibold text-stone-700 dark:text-slate-200">{company._count.vehicles} {copy.company.vehicles}</p>
                </Link>
              )
            })}
          </div>
        ) : <EmptyState copy={copy.status.unavailableBody} />}
      </section>

      <section id="how-it-works" className="site-section scroll-mt-24">
        <div className="rounded-[2.5rem] bg-blue-950 p-7 text-white sm:p-10 lg:p-14">
          <SectionHeading eyebrow="Carplace" title={copy.sections.how} inverse />
          <div className="mt-9 grid gap-6 md:grid-cols-2 lg:grid-cols-4">
            {copy.how.map(([title, body], index) => <article key={title} className="relative rounded-2xl border border-blue-800 bg-blue-900/55 p-5"><span className="grid h-9 w-9 place-items-center rounded-full bg-orange-500 text-sm font-black text-white">{index + 1}</span><h3 className="mt-5 text-lg font-black">{title}</h3><p className="mt-2 text-sm leading-6 text-blue-100">{body}</p></article>)}
          </div>
        </div>
      </section>

      <section className="site-section grid gap-8 lg:grid-cols-2">
        <div>
          <SectionHeading eyebrow="Carplace" title={copy.sections.guidance} />
          <div className="mt-6 grid gap-4">{copy.guidance.map(([title, body]) => <article key={title} className="carplace-guidance"><ShieldCheck className="mt-0.5 h-5 w-5 shrink-0 text-emerald-600" /><div><h3 className="font-black text-blue-950 dark:text-white">{title}</h3><p className="mt-1 text-sm leading-6 text-stone-600 dark:text-slate-300">{body}</p></div></article>)}</div>
        </div>
        <div id="help" className="scroll-mt-24">
          <SectionHeading eyebrow={copy.nav.help} title={copy.sections.faq} />
          <div className="mt-6 grid gap-3">{copy.faq.map(([question, answer]) => <details key={question} className="carplace-faq"><summary>{question}</summary><p>{answer}</p></details>)}</div>
        </div>
      </section>
    </main>
  )
}

function SectionHeading({ eyebrow, title, inverse = false }: { eyebrow: string; title: string; inverse?: boolean }) {
  return <div><p className={`text-xs font-bold uppercase tracking-[0.2em] ${inverse ? 'text-orange-300' : 'text-orange-600 dark:text-orange-400'}`}>{eyebrow}</p><h2 className={`mt-3 text-3xl font-black tracking-[-0.035em] sm:text-4xl ${inverse ? 'text-white' : 'text-blue-950 dark:text-white'}`}>{title}</h2></div>
}

function EmptyState({ copy }: { copy: string }) {
  return <div className="mt-6 rounded-2xl border border-dashed border-stone-300 p-8 text-center text-sm text-stone-500 dark:border-blue-800 dark:text-slate-400">{copy}</div>
}
