import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import { getCars } from "@/lib/db";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import WhatsAppButton from "@/components/WhatsAppButton";
import {
  Fuel,
  Users,
  Gauge,
  Briefcase,
  Star,
  Check,
  ArrowLeft,
  Shield,
  MapPin,
  Phone,
} from "lucide-react";

interface PageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  const cars = getCars();
  return cars.map((car) => ({ slug: car.slug }));
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const cars = getCars();
  const car = cars.find((c) => c.slug === slug);
  if (!car) return {};

  return {
    title: `${car.name} | Location ${car.pricePerDay} MAD/jour Marrakech`,
    description: `Louez une ${car.name} à Marrakech pour seulement ${car.pricePerDay} MAD/jour. ${car.transmission === "automatic" ? "Boîte automatique" : "Boîte manuelle"}, ${car.fuel}, ${car.seats} places. Assurance incluse. Réservation WhatsApp.`,
    alternates: {
      canonical: `https://www.setocar.com/cars/${slug}`,
    },
    openGraph: {
      title: `${car.name} — Location Marrakech ${car.pricePerDay} MAD/jour | Setocar`,
      description: car.description,
      url: `https://www.setocar.com/cars/${slug}`,
      images: [{ url: car.image, alt: `${car.name} location Marrakech` }],
    },
  };
}

const WHATSAPP_NUMBER = "212651621512";
const PHONE_DISPLAY = "0651621512";

export default async function CarDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const cars = getCars();
  const car = cars.find((c) => c.slug === slug);
  if (!car) notFound();

  const waMsg = encodeURIComponent(
    `Bonjour Setocar! 🚗\n\nJe souhaite louer la *${car.name}*\n💰 Prix: ${car.pricePerDay} MAD/jour\n\nPouvez-vous me confirmer la disponibilité et vos offres?\n\nMerci!`
  );

  const relatedCars = cars.filter((c) => c.id !== car.id && c.category === car.category).slice(0, 2);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Product",
    name: `${car.name} - Location Marrakech`,
    image: `https://www.setocar.com${car.image}`,
    description: car.description,
    brand: { "@type": "Brand", name: car.brand },
    offers: {
      "@type": "Offer",
      price: car.pricePerDay,
      priceCurrency: "MAD",
      priceValidUntil: "2026-12-31",
      availability: car.available
        ? "https://schema.org/InStock"
        : "https://schema.org/OutOfStock",
      seller: {
        "@type": "Organization",
        name: "Setocar",
        url: "https://www.setocar.com",
      },
    },
    aggregateRating: {
      "@type": "AggregateRating",
      ratingValue: car.rating,
      reviewCount: car.reviews,
      bestRating: 5,
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <Navbar />

      {/* Breadcrumb */}
      <div
        style={{
          background: "#1c2133",
          padding: "5.5rem 1.5rem 1.25rem",
        }}
      >
        <div style={{ maxWidth: "1280px", margin: "0 auto" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontSize: "0.82rem" }}>
            <Link href="/" style={{ color: "rgba(255,255,255,0.5)", textDecoration: "none" }}>
              Accueil
            </Link>
            <span style={{ color: "rgba(255,255,255,0.3)" }}>/</span>
            <Link href="/cars" style={{ color: "rgba(255,255,255,0.5)", textDecoration: "none" }}>
              Voitures
            </Link>
            <span style={{ color: "rgba(255,255,255,0.3)" }}>/</span>
            <span style={{ color: "#e85c1a" }}>{car.name}</span>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <section style={{ padding: "3rem 1.5rem 5rem", background: "#111520" }}>
        <div style={{ maxWidth: "1280px", margin: "0 auto" }}>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 400px",
              gap: "2.5rem",
              alignItems: "start",
            }}
            className="car-detail-grid"
          >
            {/* Left: Car Details */}
            <div>
              {/* Back button */}
              <Link
                href="/cars"
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  gap: "0.4rem",
                  color: "white",
                  textDecoration: "none",
                  fontWeight: 600,
                  fontSize: "0.88rem",
                  marginBottom: "1.5rem",
                  padding: "0.5rem 1rem",
                  background: "#1c2133",
                  borderRadius: "0.5rem",
                  border: "1px solid #2a3050",
                  transition: "all 0.2s",
                }}
              >
                <ArrowLeft size={16} /> Retour au catalogue
              </Link>

              {/* Car Image */}
              <div
                style={{
                  background: "#1c2133",
                  borderRadius: "1.5rem",
                  overflow: "hidden",
                  marginBottom: "1.5rem",
                  boxShadow: "0 10px 40px rgba(0,0,0,0.2)",
                  position: "relative",
                  border: "1px solid #2a3050",
                }}
              >
                {car.badge && (
                  <div
                    style={{
                      position: "absolute",
                      top: "1.25rem",
                      left: "1.25rem",
                      zIndex: 10,
                      background: "linear-gradient(135deg, #e85c1a, #f06a28)",
                      color: "white",
                      padding: "0.35rem 1rem",
                      borderRadius: "2rem",
                      fontSize: "0.78rem",
                      fontWeight: 800,
                    }}
                  >
                    ✦ {car.badge}
                  </div>
                )}
                <div style={{ position: "relative", width: "100%", aspectRatio: "16/9" }}>
                  <Image
                    src={car.image}
                    alt={`${car.name} location voiture Marrakech`}
                    fill
                    priority
                    style={{ objectFit: "cover" }}
                    sizes="(max-width: 1024px) 100vw, 60vw"
                  />
                </div>
              </div>

              {/* Description */}
              <div
                style={{
                  background: "#1c2133",
                  borderRadius: "1.25rem",
                  padding: "2rem",
                  marginBottom: "1.5rem",
                  boxShadow: "0 4px 20px rgba(0,0,0,0.15)",
                  border: "1px solid #2a3050",
                }}
              >
                <h2
                  style={{
                    fontFamily: "var(--font-playfair), var(--font-oswald)",
                    fontSize: "1.3rem",
                    color: "white",
                    marginBottom: "1rem",
                  }}
                >
                  Description
                </h2>
                <p style={{ color: "rgba(255,255,255,0.7)", lineHeight: 1.8, marginBottom: "1.5rem" }}>{car.description}</p>

                <h3
                  style={{
                    fontFamily: "var(--font-playfair), var(--font-oswald)",
                    fontSize: "1.1rem",
                    color: "white",
                    marginBottom: "0.875rem",
                  }}
                >
                  Équipements inclus
                </h3>
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
                    gap: "0.5rem",
                  }}
                >
                  {car.features.map((f) => (
                    <div
                      key={f}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: "0.5rem",
                        padding: "0.5rem 0.75rem",
                        background: "rgba(232,92,26,0.1)",
                        borderRadius: "0.5rem",
                        fontSize: "0.85rem",
                        color: "white",
                      }}
                    >
                      <Check size={14} color="#e85c1a" />
                      {f}
                    </div>
                  ))}
                  {/* Always included */}
                  {["Assurance tous risques", "Kilométrage illimité", "Assistance 24h/7j"].map((f) => (
                    <div
                      key={f}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: "0.5rem",
                        padding: "0.5rem 0.75rem",
                        background: "rgba(37,211,102,0.1)",
                        borderRadius: "0.5rem",
                        fontSize: "0.85rem",
                        color: "white",
                      }}
                    >
                      <Check size={14} color="#16a34a" />
                      {f}
                    </div>
                  ))}
                </div>
              </div>

              {/* Trust badges */}
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3, 1fr)",
                  gap: "1rem",
                }}
                className="trust-badges"
              >
                {[
                  { icon: <Shield size={24} color="#e85c1a" />, text: "Assurance incluse" },
                  { icon: <MapPin size={24} color="#e85c1a" />, text: "Livraison aéroport" },
                  { icon: <Phone size={24} color="#e85c1a" />, text: "Support 24/7" },
                ].map((b) => (
                  <div
                    key={b.text}
                    style={{
                      background: "#1c2133",
                      borderRadius: "1rem",
                      padding: "1.25rem",
                      textAlign: "center",
                      boxShadow: "0 4px 15px rgba(0,0,0,0.15)",
                      border: "1px solid #2a3050",
                    }}
                  >
                    <div style={{ marginBottom: "0.5rem", display: "flex", justifyContent: "center" }}>{b.icon}</div>
                    <p style={{ fontSize: "0.8rem", color: "white", fontWeight: 600 }}>{b.text}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Right: Booking Panel */}
            <div style={{ position: "sticky", top: "5rem" }}>
              <div
                style={{
                  background: "#1c2133",
                  borderRadius: "1.5rem",
                  padding: "2rem",
                  boxShadow: "0 20px 60px rgba(0,0,0,0.3)",
                  border: "1px solid #2a3050",
                }}
              >
                {/* Header */}
                <div style={{ marginBottom: "1.5rem" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: "0.4rem", marginBottom: "0.5rem" }}>
                    {Array.from({ length: 5 }, (_, i) => (
                      <Star
                        key={i}
                        size={14}
                        fill={i < Math.floor(car.rating) ? "#e85c1a" : "none"}
                        color={i < Math.floor(car.rating) ? "#e85c1a" : "#4b5563"}
                      />
                    ))}
                    <span style={{ fontSize: "0.8rem", color: "rgba(255,255,255,0.5)" }}>
                      {car.rating} ({car.reviews} avis)
                    </span>
                  </div>
                  <h1
                    style={{
                      fontFamily: "var(--font-playfair), var(--font-oswald)",
                      fontSize: "1.6rem",
                      color: "white",
                      marginBottom: "0.25rem",
                    }}
                  >
                    {car.name}
                  </h1>
                  <span
                    style={{
                      display: "inline-block",
                      background: "rgba(232,92,26,0.1)",
                      color: "#e85c1a",
                      padding: "0.2rem 0.75rem",
                      borderRadius: "2rem",
                      fontSize: "0.75rem",
                      fontWeight: 600,
                    }}
                  >
                    {car.categoryLabel}
                  </span>
                </div>

                {/* Price */}
                <div
                  style={{
                    background: "#111520",
                    borderRadius: "1rem",
                    padding: "1.5rem",
                    textAlign: "center",
                    marginBottom: "1.5rem",
                    border: "1px solid #2a3050",
                  }}
                >
                  <p style={{ color: "rgba(255,255,255,0.7)", fontSize: "0.82rem", marginBottom: "0.25rem" }}>
                    Prix par jour
                  </p>
                  <div style={{ display: "flex", alignItems: "baseline", justifyContent: "center", gap: "0.4rem" }}>
                    <span
                      style={{
                        fontFamily: "var(--font-playfair), var(--font-oswald)",
                        fontSize: "3rem",
                        fontWeight: 800,
                        color: "#e85c1a",
                      }}
                    >
                      {car.pricePerDay}
                    </span>
                    <span style={{ color: "rgba(255,255,255,0.7)", fontSize: "1rem" }}>MAD</span>
                  </div>
                  <p style={{ color: "rgba(255,255,255,0.6)", fontSize: "0.78rem", marginTop: "0.25rem" }}>
                    Assurance + GPS + km illimité inclus
                  </p>
                </div>

                {/* Specs grid */}
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "1fr 1fr",
                    gap: "0.75rem",
                    marginBottom: "1.5rem",
                  }}
                >
                  {[
                    { icon: <Fuel size={16} color="#e85c1a" />, label: "Carburant", value: car.fuel },
                    {
                      icon: <Gauge size={16} color="#e85c1a" />,
                      label: "Boîte",
                      value: car.transmission === "automatic" ? "Automatique" : "Manuelle",
                    },
                    { icon: <Users size={16} color="#e85c1a" />, label: "Places", value: `${car.seats} places` },
                    { icon: <Briefcase size={16} color="#e85c1a" />, label: "Bagages", value: `${car.luggage} valises` },
                  ].map((spec) => (
                    <div
                      key={spec.label}
                      style={{
                        background: "#111520",
                        borderRadius: "0.75rem",
                        padding: "0.875rem",
                        display: "flex",
                        alignItems: "center",
                        gap: "0.5rem",
                        border: "1px solid #2a3050",
                      }}
                    >
                      {spec.icon}
                      <div>
                        <p style={{ fontSize: "0.7rem", color: "rgba(255,255,255,0.5)", fontWeight: 500 }}>{spec.label}</p>
                        <p style={{ fontSize: "0.85rem", color: "white", fontWeight: 700 }}>{spec.value}</p>
                      </div>
                    </div>
                  ))}
                </div>

                {/* CTAs */}
                <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
                  <a
                    href={`https://wa.me/${WHATSAPP_NUMBER}?text=${waMsg}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    id={`whatsapp-book-${car.slug}`}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: "0.75rem",
                      padding: "1rem",
                      background: "#25d366",
                      borderRadius: "0.75rem",
                      color: "white",
                      textDecoration: "none",
                      fontWeight: 700,
                      fontSize: "1rem",
                      boxShadow: "0 4px 15px rgba(37,211,102,0.3)",
                      transition: "all 0.3s ease",
                    }}
                  >
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="white">
                      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                    </svg>
                    Réserver via WhatsApp
                  </a>
                  <a
                    href={`tel:${PHONE_DISPLAY}`}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: "0.5rem",
                      padding: "0.875rem",
                      background: "#111520",
                      borderRadius: "0.75rem",
                      color: "white",
                      textDecoration: "none",
                      fontWeight: 600,
                      fontSize: "0.9rem",
                      border: "1px solid #2a3050",
                      transition: "all 0.2s",
                    }}
                  >
                    <Phone size={16} color="#e85c1a" /> Appeler maintenant
                  </a>
                </div>

                <p
                  style={{
                    textAlign: "center",
                    color: "rgba(255,255,255,0.4)",
                    fontSize: "0.78rem",
                    marginTop: "1rem",
                  }}
                >
                  🔒 Confirmation en moins de 10 minutes · Annulation gratuite
                </p>
              </div>
            </div>
          </div>

          {/* Related Cars */}
          {relatedCars.length > 0 && (
            <div style={{ marginTop: "4rem" }}>
              <h2
                style={{
                  fontFamily: "var(--font-playfair), var(--font-oswald)",
                  fontSize: "1.5rem",
                  color: "white",
                  marginBottom: "1.5rem",
                }}
              >
                Véhicules similaires
              </h2>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fill, minmax(300px, 1fr))",
                  gap: "1.5rem",
                }}
              >
                {relatedCars.map((c) => (
                  <Link
                    key={c.id}
                    href={`/cars/${c.slug}`}
                    style={{ textDecoration: "none" }}
                  >
                    <div
                      className="card-hover"
                      style={{
                        background: "#1c2133",
                        borderRadius: "1rem",
                        padding: "1.25rem",
                        display: "flex",
                        gap: "1rem",
                        alignItems: "center",
                        boxShadow: "0 4px 15px rgba(0,0,0,0.2)",
                        border: "1px solid #2a3050",
                        transition: "all 0.3s ease",
                      }}
                    >
                      <div
                        style={{
                          position: "relative",
                          width: 120,
                          height: 80,
                          flexShrink: 0,
                          background: "#111520",
                          borderRadius: "0.5rem",
                          overflow: "hidden",
                        }}
                      >
                        <Image
                          src={c.image}
                          alt={c.name}
                          fill
                          style={{ objectFit: "contain", padding: "0.5rem" }}
                          sizes="120px"
                        />
                      </div>
                      <div>
                        <p style={{ fontWeight: 700, color: "white", fontSize: "0.95rem" }}>{c.name}</p>
                        <p style={{ color: "#e85c1a", fontWeight: 800, fontSize: "1.1rem" }}>
                          {c.pricePerDay} MAD/jour
                        </p>
                        <p style={{ color: "rgba(255,255,255,0.5)", fontSize: "0.78rem" }}>{c.categoryLabel}</p>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          )}
        </div>
      </section>
      <style>{`
        @media (max-width: 900px) {
          .car-detail-grid {
            grid-template-columns: 1fr !important;
          }
        }
        @media (max-width: 600px) {
          .trust-badges {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
      <Footer />
      <WhatsAppButton />
    </>
  );
}
