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

interface Offer {
  id: string
  title: string
  description: string | null
  discountValue: number
  validUntil: string
}

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

export default async function OffersPage() {
  const dict = getPublicSiteDictionary(getPublicSiteLanguage())
  const [offers, brand] = await Promise.all([
    siteFetch<Offer[]>(`/site/${DEFAULT_COMPANY_SLUG}/offers`).catch(() => []),
    siteFetch<BrandResponse>(`/site/${DEFAULT_COMPANY_SLUG}/brand`).catch(() => null),
  ])
  const pageSections = resolvePageSectionsConfig(brand?.brand?.menuConfig)
  return (
    <main className="min-h-screen bg-slate-50 py-10">
      <div className="shell">
        {pageSections.offers.header ? <h1 className="text-4xl font-black text-slate-900">{dict.offers.title}</h1> : null}
        {pageSections.offers.grid ? <div className={`${pageSections.offers.header ? 'mt-8' : ''} grid gap-5 md:grid-cols-2 xl:grid-cols-3`}>
          {offers.map((offer) => (
            <div key={offer.id} className="card p-6">
              <h2 className="text-xl font-bold text-slate-900">{offer.title}</h2>
              <p className="mt-3 text-3xl font-black text-sky-700">{offer.discountValue}%</p>
              <p className="mt-3 text-sm text-slate-600">{offer.description ?? dict.offers.noDescription}</p>
              <Link href={`/book?offerId=${offer.id}`} className="mt-6 inline-block rounded-full bg-slate-900 px-5 py-2.5 text-sm font-semibold text-white">{dict.offers.bookOffer}</Link>
            </div>
          ))}
          {offers.length === 0 && <div className="card p-6 text-sm text-slate-500">{dict.offers.empty}</div>}
        </div> : null}
      </div>
    </main>
  )
}
