import Link from 'next/link'
import { storefrontFetchOrDefault } from '@/lib/api'
import { getStorefrontLanguage } from '@/lib/i18n.server'
import { formatCurrency } from '@rentaldrivego/types'
import BookingForm from '@/components/BookingForm'

interface VehicleDetail {
  id: string
  make: string
  model: string
  year: number
  category: string
  seats: number
  transmission: string
  fuelType: string
  features: string[]
  dailyRate: number
  photos: string[]
  pickupLocations: string[]
  allowDifferentDropoff: boolean
  dropoffLocations: 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 = await getStorefrontLanguage()
  const dict = {
    en: {
      unavailable: 'Storefront unavailable',
      unavailableTitle: 'Vehicle details are temporarily unavailable.',
      unavailableBody: 'The storefront frontend is running, but the backing database is not reachable right now.',
      backToFleet: 'Back to fleet',
      backToExplore: 'Back to explore',
      noPhotos: 'No photos available.',
      rentalCompany: 'Rental company',
      perDay: '/ day',
      availableFrom: 'Available from',
      unavailableNoDate: 'This vehicle is temporarily unavailable for new reservations.',
      specs: 'Specifications',
      year: 'Year',
      category: 'Category',
      seats: 'Seats',
      transmission: 'Transmission',
      fuel: 'Fuel type',
      features: 'Features & extras',
      contact: 'Contact company',
      phone: 'Phone',
      whatsapp: 'WhatsApp',
      photos: 'Photos',
    },
    fr: {
      unavailable: 'Storefront indisponible',
      unavailableTitle: 'Les détails du véhicule sont temporairement indisponibles.',
      unavailableBody: "Le frontend storefront fonctionne, mais la base de données n'est pas accessible pour le moment.",
      backToFleet: 'Retour à la flotte',
      backToExplore: 'Retour à l’exploration',
      noPhotos: 'Aucune photo disponible.',
      rentalCompany: 'Société de location',
      perDay: '/ jour',
      availableFrom: 'Disponible à partir du',
      unavailableNoDate: 'Ce véhicule est temporairement indisponible pour les nouvelles réservations.',
      specs: 'Caractéristiques',
      year: 'Année',
      category: 'Catégorie',
      seats: 'Places',
      transmission: 'Transmission',
      fuel: 'Carburant',
      features: 'Équipements & extras',
      contact: 'Contacter la société',
      phone: 'Téléphone',
      whatsapp: 'WhatsApp',
      photos: 'Photos',
    },
    ar: {
      unavailable: 'السوق غير متاح',
      unavailableTitle: 'تفاصيل السيارة غير متاحة مؤقتاً.',
      unavailableBody: 'واجهة السوق تعمل، لكن قاعدة البيانات في الخلفية غير متاحة حالياً.',
      backToFleet: 'العودة إلى الأسطول',
      backToExplore: 'العودة إلى الاستكشاف',
      noPhotos: 'لا توجد صور متاحة.',
      rentalCompany: 'شركة تأجير',
      perDay: '/ يوم',
      availableFrom: 'متاح ابتداءً من',
      unavailableNoDate: 'هذه السيارة غير متاحة مؤقتاً للحجوزات الجديدة.',
      specs: 'المواصفات',
      year: 'السنة',
      category: 'الفئة',
      seats: 'المقاعد',
      transmission: 'ناقل الحركة',
      fuel: 'نوع الوقود',
      features: 'المميزات والإضافات',
      contact: 'تواصل مع الشركة',
      phone: 'الهاتف',
      whatsapp: 'واتساب',
      photos: 'الصور',
    },
  }[language]

  const vehicle = await storefrontFetchOrDefault<VehicleDetail | null>(`/storefront/${params.slug}/vehicles/${params.id}`, null)

  if (!vehicle) {
    return (
      <main className="site-page">
        <div className="site-section">
          <section className="card p-8">
            <p className="text-sm uppercase tracking-[0.18em] text-orange-700 dark:text-orange-400">{dict.unavailable}</p>
            <h1 className="mt-3 text-3xl font-black text-stone-900 dark:text-stone-100">{dict.unavailableTitle}</h1>
            <p className="mt-3 text-stone-600 dark:text-stone-400">{dict.unavailableBody}</p>
            <div className="mt-6 flex gap-3">
              <Link href={`/explore/${params.slug}`} className="rounded-full bg-blue-900 px-5 py-2.5 text-sm font-semibold text-white transition hover:bg-orange-700 dark:bg-orange-500 dark:text-white dark:hover:bg-orange-400">{dict.backToFleet}</Link>
              <Link href="/explore" className="rounded-full border border-stone-200 px-5 py-2.5 text-sm font-semibold text-stone-700 transition hover:border-stone-400 dark:border-blue-800 dark:text-stone-300 dark:hover:border-stone-500">{dict.backToExplore}</Link>
            </div>
          </section>
        </div>
      </main>
    )
  }

  const availabilityDate = vehicle.nextAvailableAt
    ? new Date(vehicle.nextAvailableAt).toLocaleDateString('en-GB', { year: 'numeric', month: 'long', day: 'numeric' })
    : null

  const [heroPhoto, ...galleryPhotos] = vehicle.photos

  return (
    <main className="site-page">
      <div className="site-section space-y-8">

        {/* Breadcrumb */}
        <nav className="flex items-center gap-2 text-sm text-stone-500 dark:text-stone-400">
          <Link href="/explore" className="hover:text-stone-900 dark:hover:text-stone-100 transition">{dict.backToExplore}</Link>
          <span>/</span>
          <Link href={`/explore/${params.slug}`} className="hover:text-stone-900 dark:hover:text-stone-100 transition">{vehicle.company.brand?.displayName ?? dict.rentalCompany}</Link>
          <span>/</span>
          <span className="text-stone-900 dark:text-stone-100 font-medium">{vehicle.make} {vehicle.model}</span>
        </nav>

        <div className="grid gap-8 lg:grid-cols-[1fr_380px]">

          {/* Left — photos + specs */}
          <div className="space-y-6">

            {/* Hero photo */}
            {heroPhoto ? (
              <div className="overflow-hidden rounded-3xl bg-stone-100 dark:bg-blue-900/30 aspect-[16/9]">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={heroPhoto} alt={`${vehicle.make} ${vehicle.model}`} className="h-full w-full object-cover" />
              </div>
            ) : (
              <div className="overflow-hidden rounded-3xl bg-stone-100 dark:bg-blue-900/30 aspect-[16/9] flex items-center justify-center text-sm text-stone-400">{dict.noPhotos}</div>
            )}

            {/* Gallery */}
            {galleryPhotos.length > 0 && (
              <div>
                <p className="mb-3 text-xs font-semibold uppercase tracking-[0.16em] text-stone-400 dark:text-stone-500">{dict.photos}</p>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
                  {galleryPhotos.map((photo, index) => (
                    <div key={`${photo}-${index}`} className="overflow-hidden rounded-2xl bg-stone-100 dark:bg-blue-900/30 aspect-[4/3]">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img src={photo} alt={`${vehicle.make} ${vehicle.model} ${index + 2}`} className="h-full w-full object-cover" />
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Specs */}
            <div className="card p-6 space-y-4">
              <h2 className="text-lg font-bold text-stone-900 dark:text-stone-100">{dict.specs}</h2>
              <dl className="grid grid-cols-2 gap-x-6 gap-y-4 sm:grid-cols-3">
                <div>
                  <dt className="text-xs font-medium uppercase tracking-[0.14em] text-stone-400 dark:text-stone-500">{dict.year}</dt>
                  <dd className="mt-1 text-base font-semibold text-stone-900 dark:text-stone-100">{vehicle.year}</dd>
                </div>
                <div>
                  <dt className="text-xs font-medium uppercase tracking-[0.14em] text-stone-400 dark:text-stone-500">{dict.category}</dt>
                  <dd className="mt-1 text-base font-semibold text-stone-900 dark:text-stone-100">{vehicle.category}</dd>
                </div>
                {vehicle.seats > 0 && (
                  <div>
                    <dt className="text-xs font-medium uppercase tracking-[0.14em] text-stone-400 dark:text-stone-500">{dict.seats}</dt>
                    <dd className="mt-1 text-base font-semibold text-stone-900 dark:text-stone-100">{vehicle.seats}</dd>
                  </div>
                )}
                {vehicle.transmission && (
                  <div>
                    <dt className="text-xs font-medium uppercase tracking-[0.14em] text-stone-400 dark:text-stone-500">{dict.transmission}</dt>
                    <dd className="mt-1 text-base font-semibold text-stone-900 dark:text-stone-100">{vehicle.transmission}</dd>
                  </div>
                )}
                {vehicle.fuelType && (
                  <div>
                    <dt className="text-xs font-medium uppercase tracking-[0.14em] text-stone-400 dark:text-stone-500">{dict.fuel}</dt>
                    <dd className="mt-1 text-base font-semibold text-stone-900 dark:text-stone-100">{vehicle.fuelType}</dd>
                  </div>
                )}
              </dl>

              {vehicle.features.length > 0 && (
                <div className="pt-2 border-t border-stone-100 dark:border-blue-900">
                  <p className="text-xs font-medium uppercase tracking-[0.14em] text-stone-400 dark:text-stone-500 mb-3">{dict.features}</p>
                  <div className="flex flex-wrap gap-2">
                    {vehicle.features.map((feature) => (
                      <span key={feature} className="rounded-full bg-stone-100 dark:bg-blue-900/30 px-3 py-1 text-xs font-medium text-stone-700 dark:text-stone-300">{feature}</span>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Contact */}
            {(vehicle.company.brand?.publicPhone || vehicle.company.brand?.whatsappNumber) && (
              <div className="card p-6 space-y-3">
                <h2 className="text-lg font-bold text-stone-900 dark:text-stone-100">{dict.contact}</h2>
                <p className="text-sm text-stone-500 dark:text-stone-400">{vehicle.company.brand?.displayName ?? dict.rentalCompany}</p>
                <div className="flex flex-wrap gap-3">
                  {vehicle.company.brand?.publicPhone && (
                    <a href={`tel:${vehicle.company.brand.publicPhone}`} className="inline-flex items-center gap-2 rounded-full border border-stone-300 dark:border-blue-800 px-4 py-2 text-sm font-semibold text-stone-700 dark:text-stone-300 hover:bg-stone-100 dark:hover:bg-blue-900/40 transition">
                      {dict.phone}: {vehicle.company.brand.publicPhone}
                    </a>
                  )}
                  {vehicle.company.brand?.whatsappNumber && (
                    <a href={`https://wa.me/${vehicle.company.brand.whatsappNumber.replace(/\D/g, '')}`} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 rounded-full bg-orange-600 px-4 py-2 text-sm font-semibold text-white hover:bg-orange-700 transition">
                      {dict.whatsapp}
                    </a>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Right — sticky booking panel */}
          <aside className="space-y-4">
            <div className="card p-6 space-y-4 lg:sticky lg:top-20">
              <p className="text-xs uppercase tracking-[0.18em] text-stone-500 dark:text-stone-400">{vehicle.company.brand?.displayName ?? dict.rentalCompany}</p>
              <h1 className="text-3xl font-black text-stone-900 dark:text-stone-100">{vehicle.make} {vehicle.model}</h1>
              <p className="text-stone-500 dark:text-stone-400">{vehicle.year} · {vehicle.category}</p>
              <p className="text-3xl font-black text-stone-900 dark:text-stone-100">
                {formatCurrency(vehicle.dailyRate, 'MAD', language)}
                <span className="text-base font-medium text-stone-500 dark:text-stone-400"> {dict.perDay}</span>
              </p>

              {!vehicle.availability && (
                <div className="rounded-2xl border border-orange-200 bg-orange-50 dark:border-orange-800 dark:bg-orange-950/40 px-4 py-3 text-sm text-orange-800 dark:text-orange-300">
                  {availabilityDate ? `${dict.availableFrom} ${availabilityDate}` : dict.unavailableNoDate}
                </div>
              )}

              {vehicle.availability && (
                <BookingForm
                  vehicleId={vehicle.id}
                  companySlug={params.slug}
                  dailyRate={vehicle.dailyRate}
                  pickupLocations={vehicle.pickupLocations}
                  allowDifferentDropoff={vehicle.allowDifferentDropoff}
                  dropoffLocations={vehicle.dropoffLocations}
                />
              )}

              <Link
                href={`/explore/${params.slug}`}
                className="block rounded-full border border-stone-300 dark:border-blue-800 px-6 py-3 text-center text-sm font-semibold text-stone-700 dark:text-stone-300 hover:bg-stone-100 dark:hover:bg-blue-900/40 transition"
              >
                {dict.backToFleet}
              </Link>
            </div>
          </aside>
        </div>
      </div>
    </main>
  )
}
