import Link from 'next/link'
import { marketplaceFetchOrDefault } from '@/lib/api'
import { getMarketplaceLanguage } from '@/lib/i18n.server'
import { formatCurrency } from '@rentaldrivego/types'

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

export default async function VehicleDetailPage({ params }: { params: { slug: string; id: string } }) {
  const language = getMarketplaceLanguage()
  const dict = {
    en: {
      unavailable: 'Marketplace unavailable',
      unavailableTitle: 'Vehicle details are temporarily unavailable.',
      unavailableBody: 'The marketplace frontend is running, but the backing database is not reachable right now.',
      backToFleet: 'Back to company fleet',
      noPhotos: 'No photos available.',
      rentalCompany: 'Rental company',
      perDay: '/ day',
      continueTo: 'Continue to',
      bookingSite: 'booking site',
      availableFrom: 'Available from',
      unavailableNoDate: 'This vehicle is temporarily unavailable for new reservations.',
    },
    fr: {
      unavailable: 'Marketplace indisponible',
      unavailableTitle: 'Les détails du véhicule sont temporairement indisponibles.',
      unavailableBody: 'Le frontend marketplace fonctionne, mais la base de données n’est pas accessible pour le moment.',
      backToFleet: 'Retour à la flotte',
      noPhotos: 'Aucune photo disponible.',
      rentalCompany: 'Société de location',
      perDay: '/ jour',
      continueTo: 'Continuer vers le site de réservation de',
      bookingSite: '',
      availableFrom: 'Disponible à partir du',
      unavailableNoDate: 'Ce véhicule est temporairement indisponible pour les nouvelles réservations.',
    },
    ar: {
      unavailable: 'السوق غير متاح',
      unavailableTitle: 'تفاصيل السيارة غير متاحة مؤقتاً.',
      unavailableBody: 'واجهة السوق تعمل، لكن قاعدة البيانات الخلفية غير متاحة حالياً.',
      backToFleet: 'العودة إلى أسطول الشركة',
      noPhotos: 'لا توجد صور متاحة.',
      rentalCompany: 'شركة تأجير',
      perDay: '/ يوم',
      continueTo: 'الانتقال إلى موقع حجز',
      bookingSite: '',
      availableFrom: 'متاح ابتداءً من',
      unavailableNoDate: 'هذه السيارة غير متاحة مؤقتاً للحجوزات الجديدة.',
    },
  }[language]
  const vehicle = await marketplaceFetchOrDefault<VehicleDetail | null>(`/marketplace/${params.slug}/vehicles/${params.id}`, null)

  if (!vehicle) {
    return (
      <main className="min-h-screen bg-stone-50 py-10">
        <div className="shell">
          <section className="card p-8">
            <p className="text-sm uppercase tracking-[0.18em] text-amber-700">{dict.unavailable}</p>
            <h1 className="mt-3 text-3xl font-black text-stone-900">{dict.unavailableTitle}</h1>
            <p className="mt-3 text-stone-600">{dict.unavailableBody}</p>
            <div className="mt-6">
              <Link href={`/explore/${params.slug}`} className="rounded-full bg-stone-900 px-5 py-2.5 text-sm font-semibold text-white">{dict.backToFleet}</Link>
            </div>
          </section>
        </div>
      </main>
    )
  }

  const destination = `https://${params.slug}.RentalDriveGo.com/book?vehicleId=${vehicle.id}&ref=marketplace`
  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-stone-50 py-10">
      <div className="shell grid gap-8 lg:grid-cols-[1.2fr_0.8fr]">
        <section className="space-y-4">
          <div 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>
            ))}
            {vehicle.photos.length === 0 && <div className="card p-8 text-sm text-stone-500">{dict.noPhotos}</div>}
          </div>
        </section>
        <aside className="card p-6 h-fit">
          <p className="text-xs uppercase tracking-[0.18em] text-stone-500">{vehicle.company.brand?.displayName ?? dict.rentalCompany}</p>
          <h1 className="mt-3 text-4xl font-black text-stone-900">{vehicle.make} {vehicle.model}</h1>
          <p className="mt-3 text-stone-600">{vehicle.year} · {vehicle.category} · {vehicle.transmission}</p>
          <p className="mt-6 text-3xl font-black text-stone-900">{formatCurrency(vehicle.dailyRate, 'MAD')}<span className="text-base font-medium text-stone-500"> {dict.perDay}</span></p>
          {!vehicle.availability && (
            <div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
              {availabilityDate ? `${dict.availableFrom} ${availabilityDate}` : dict.unavailableNoDate}
            </div>
          )}
          <div className="mt-6 flex flex-wrap gap-2">
            {vehicle.features.map((feature) => (
              <span key={feature} className="rounded-full bg-stone-100 px-3 py-1 text-xs font-medium text-stone-700">{feature}</span>
            ))}
          </div>
          <div className="mt-8 space-y-3">
            <Link href={destination} className="block rounded-full bg-stone-900 px-6 py-3 text-center text-sm font-semibold text-white">{dict.continueTo} {vehicle.company.brand?.displayName ?? dict.rentalCompany} {dict.bookingSite}</Link>
            <Link href={`/explore/${params.slug}`} className="block rounded-full border border-stone-300 px-6 py-3 text-center text-sm font-semibold text-stone-700">{dict.backToFleet}</Link>
          </div>
        </aside>
      </div>
    </main>
  )
}
