import { BadgeCheck, Building2, CalendarDays, MapPin, MessageCircle, Phone, ShieldCheck, Star } from 'lucide-react'
import Link from 'next/link'
import VehicleCard from '@/components/carplace/VehicleCard'
import { getCarplaceMessages } from '@/lib/carplace/messages'
import { formatOfferValue } from '@/lib/carplace/offers'
import { carplaceHref } from '@/lib/carplace/routes'
import type { CompanyBrand, OfferSummary, VehicleSummary } from '@/lib/carplace/types'
import { carplaceFetchOrDefault } from '@/lib/api'
import { getCarplaceLanguage } from '@/lib/i18n.server'

interface CompanyProfile {
  id: string
  name: string
  slug: string
  brand: (CompanyBrand & Record<string, unknown>) | null
  vehicles: Array<Omit<VehicleSummary, 'company'>>
  offers: OfferSummary[]
}

interface Review {
  id: string
  overallRating: number
  comment?: string | null
  createdAt: string
  renter?: { firstName: string; lastName: string }
}

export default async function CarplaceCompanyPage({ params }: { params: Promise<{ slug: string }> }) {
  const resolvedParams = await params
  const { slug } = resolvedParams
  const language = await getCarplaceLanguage()
  const copy = getCarplaceMessages(language)
  const [company, reviews] = await Promise.all([
    carplaceFetchOrDefault<CompanyProfile | null>(`/carplace/${encodeURIComponent(slug)}`, null),
    carplaceFetchOrDefault<Review[]>(`/carplace/${encodeURIComponent(slug)}/reviews`, []),
  ])

  if (!company) {
    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"><Building2 className="mx-auto h-12 w-12 text-stone-400" /><h1 className="mt-5 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 brand = company.brand
  const name = brand?.displayName || company.name
  const vehicles: VehicleSummary[] = company.vehicles.map((vehicle) => ({ ...vehicle, company: { slug: company.slug, brand } }))
  const description = localizedBrandValue(brand, 'description', language)
  const policies = [
    localizedBrandValue(brand, 'depositPolicySummary', language),
    localizedBrandValue(brand, 'mileagePolicySummary', language),
    localizedBrandValue(brand, 'cancellationPolicySummary', language),
    localizedBrandValue(brand, 'requiredDocumentsSummary', language),
  ].filter(Boolean)

  return (
    <main className="site-page" id="main-content">
      <section className="relative overflow-hidden border-b border-stone-200 bg-blue-950 text-white dark:border-blue-900">
        {typeof brand?.coverImageUrl === 'string' && brand.coverImageUrl ? <div className="absolute inset-0 opacity-30"><img src={brand.coverImageUrl} alt="" className="h-full w-full object-cover" /></div> : null}
        <div className="absolute inset-0 bg-gradient-to-r from-blue-950 via-blue-950/90 to-blue-900/60" />
        <div className="shell relative py-12 sm:py-16">
          <nav className="text-sm text-blue-200"><Link href={carplaceHref()} className="text-blue-200 no-underline hover:text-white">Carplace</Link><span className="mx-2">/</span><span>{name}</span></nav>
          <div className="mt-8 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
            <div className="max-w-3xl">
              <p className="flex items-center gap-2 text-xs font-bold uppercase tracking-[0.18em] text-orange-300"><BadgeCheck className="h-4 w-4" />{copy.company.partner}</p>
              <h1 className="mt-4 text-4xl font-black tracking-[-0.04em] sm:text-5xl">{name}</h1>
              {description ? <p className="mt-5 max-w-2xl text-base leading-8 text-blue-100">{description}</p> : null}
              <div className="mt-6 flex flex-wrap gap-3 text-sm text-blue-100">
                {brand?.publicCity ? <span className="carplace-dark-pill"><MapPin className="h-4 w-4" />{brand.publicCity}{brand.publicCountry ? `, ${brand.publicCountry}` : ''}</span> : null}
                <span className="carplace-dark-pill"><CalendarDays className="h-4 w-4" />{vehicles.length} {copy.company.vehicles}</span>
                {brand?.carplaceRating ? <span className="carplace-dark-pill"><Star className="h-4 w-4 fill-current text-amber-300" />{brand.carplaceRating.toFixed(1)} · {reviews.length} {copy.company.reviews}</span> : null}
              </div>
            </div>
            <div className="flex flex-wrap gap-3">
              {brand?.publicPhone ? <a href={`tel:${brand.publicPhone}`} className="carplace-light-button"><Phone className="h-4 w-4" />{copy.vehicle.phone}</a> : null}
              {brand?.whatsappNumber ? <a href={`https://wa.me/${brand.whatsappNumber.replace(/\D/g, '')}`} target="_blank" rel="noreferrer" className="carplace-orange-button"><MessageCircle className="h-4 w-4" />{copy.vehicle.whatsapp}</a> : null}
            </div>
          </div>
        </div>
      </section>

      <div className="shell py-12">
        {company.offers.length > 0 ? <section><h2 className="text-2xl font-black text-blue-950 dark:text-white">{copy.company.offers}</h2><div className="mt-5 grid gap-4 md:grid-cols-2 lg:grid-cols-3">{company.offers.map((offer) => <article key={offer.id} className="rounded-2xl border border-orange-200 bg-orange-50 p-5 dark:border-orange-900 dark:bg-orange-950/30"><div className="flex items-start justify-between gap-3"><h3 className="font-black text-blue-950 dark:text-white">{offer.title}</h3><span className="rounded-xl bg-orange-600 px-3 py-1.5 text-lg font-black text-white">{formatOfferValue(offer, language)}</span></div><p className="mt-4 text-xs text-stone-500 dark:text-slate-400">{new Intl.DateTimeFormat(language === 'ar' ? 'ar-MA' : language === 'fr' ? 'fr-MA' : 'en-MA', { dateStyle: 'medium' }).format(new Date(offer.validUntil))}</p></article>)}</div></section> : null}

        <section className={company.offers.length > 0 ? 'mt-14' : ''}>
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between"><div><p className="text-xs font-bold uppercase tracking-[0.18em] text-orange-600 dark:text-orange-400">{name}</p><h2 className="mt-2 text-3xl font-black tracking-[-0.035em] text-blue-950 dark:text-white">{copy.company.fleet}</h2></div><Link href={`${carplaceHref('/search')}?pickupLocation=${encodeURIComponent(brand?.publicCity || '')}`} className="carplace-secondary-button">{copy.actions.search}</Link></div>
          {vehicles.length > 0 ? <div className="mt-7 grid gap-6 md:grid-cols-2 xl:grid-cols-3">{vehicles.map((vehicle) => <VehicleCard key={vehicle.id} vehicle={vehicle} copy={copy} language={language} />)}</div> : <p className="mt-6 rounded-2xl border border-dashed border-stone-300 p-8 text-center text-stone-500 dark:border-blue-800 dark:text-slate-400">{copy.results.none}</p>}
        </section>

        <div className="mt-14 grid gap-6 lg:grid-cols-2">
          <section className="rounded-[2rem] border border-stone-200 bg-white p-7 dark:border-blue-900 dark:bg-blue-950"><h2 className="flex items-center gap-2 text-xl font-black text-blue-950 dark:text-white"><ShieldCheck className="h-5 w-5 text-emerald-600" />{copy.company.policies}</h2>{policies.length > 0 ? <ul className="mt-5 grid gap-3 text-sm leading-6 text-stone-600 dark:text-slate-300">{policies.map((policy) => <li key={policy} className="rounded-xl bg-stone-50 p-4 dark:bg-blue-900/30">{policy}</li>)}</ul> : <p className="mt-4 text-sm leading-6 text-stone-500 dark:text-slate-400">{copy.vehicle.estimateDisclaimer}</p>}</section>
          <section className="rounded-[2rem] border border-stone-200 bg-white p-7 dark:border-blue-900 dark:bg-blue-950"><h2 className="flex items-center gap-2 text-xl font-black text-blue-950 dark:text-white"><Star className="h-5 w-5 text-amber-500" />{copy.vehicle.rating}</h2>{reviews.length > 0 ? <div className="mt-5 grid gap-4">{reviews.slice(0, 4).map((review) => <blockquote key={review.id} className="rounded-xl bg-stone-50 p-4 dark:bg-blue-900/30"><p className="font-bold text-amber-600">{'★'.repeat(Math.max(1, Math.min(5, review.overallRating)))}</p>{review.comment ? <p className="mt-2 text-sm leading-6 text-stone-600 dark:text-slate-300">“{review.comment}”</p> : null}<footer className="mt-2 text-xs text-stone-500">{review.renter ? `${review.renter.firstName} ${review.renter.lastName.slice(0, 1)}.` : copy.vehicle.new}</footer></blockquote>)}</div> : <p className="mt-4 text-sm text-stone-500 dark:text-slate-400">{copy.vehicle.new}</p>}</section>
        </div>
      </div>
    </main>
  )
}

function localizedBrandValue(brand: (CompanyBrand & Record<string, unknown>) | null, key: string, language: 'en' | 'fr' | 'ar'): string | null {
  if (!brand) return null
  const localized = brand[`${key}${language.toUpperCase()}`]
  if (typeof localized === 'string' && localized.trim()) return localized.trim()
  const direct = brand[key]
  return typeof direct === 'string' && direct.trim() ? direct.trim() : null
}
