import type { Metadata } from "next"
import { notFound } from "next/navigation"
import Link from "next/link"
import PageHeader from "@/components/page-header"
import { SafeImage } from "@/components/safe-image"
import BlogLayout from "@/components/blog-layout"
import { blogArticles } from "@/lib/blog-utils" // Import des vrais articles

// Fonction améliorée pour normaliser les slugs (retirer les accents et remplacer les espaces par des tirets)
function normalizeSlug(text: string): string {
  return text
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "") // Supprime les accents
    .toLowerCase()
    .replace(/\s+/g, "-") // Remplace les espaces par des tirets
    .replace(/[^a-z0-9-]/g, "") // Supprime les caractères non alphanumériques (sauf tirets)
}

// Liste des catégories valides (format normalisé)
const validCategories = [
  "guide",
  "reglementation",
  "investissement",
  "assurance",
  "fiscalite",
  "renovation",
  "gestion-locative",
]

// Mapping des slugs vers les noms d'affichage
const categoryDisplayNames = {
  guide: "Guide",
  reglementation: "Réglementation",
  investissement: "Investissement",
  assurance: "Assurance",
  fiscalite: "Fiscalité",
  renovation: "Rénovation",
  "gestion-locative": "Gestion locative",
}

// Fonction utilitaire pour formater les dates de manière cohérente
function formatDate(dateString: string): string {
  // Si la date est déjà formatée (ex: "15 mars 2025"), on la retourne telle quelle
  if (dateString.includes(" ")) {
    return dateString
  }

  const options: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "long",
    day: "numeric",
  }
  return new Date(dateString).toLocaleDateString("fr-FR", options)
}

// Générer les métadonnées dynamiquement
export async function generateMetadata({ params }: { params: { category: string } }): Promise<Metadata> {
  // Normaliser la catégorie reçue
  const normalizedCategory = normalizeSlug(params.category)

  // Vérifier si la catégorie est valide
  if (!validCategories.includes(normalizedCategory)) {
    return {
      title: "Catégorie non trouvée | Blog DOGES",
      description: "La catégorie que vous recherchez n'existe pas.",
    }
  }

  const displayName = categoryDisplayNames[normalizedCategory as keyof typeof categoryDisplayNames]

  return {
    title: `Articles sur ${displayName} | Blog DOGES`,
    description: `Découvrez nos articles d'experts sur ${displayName.toLowerCase()} pour les propriétaires bailleurs à Paris et en Île-de-France.`,
    alternates: {
      canonical: `https://www.dogesadb.fr/blog/categories/${normalizedCategory}`,
    },
  }
}

export default function CategoryPage({
  params,
  searchParams,
}: {
  params: { category: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  // Normaliser la catégorie reçue
  const normalizedCategory = normalizeSlug(params.category)

  // Vérifier si la catégorie est valide
  if (!validCategories.includes(normalizedCategory)) {
    notFound()
  }

  const displayName = categoryDisplayNames[normalizedCategory as keyof typeof categoryDisplayNames]

  // Récupérer la page actuelle depuis les paramètres d'URL
  const currentPage = typeof searchParams.page === "string" ? Number.parseInt(searchParams.page) : 1

  // Filtrer les articles par catégorie (en normalisant les catégories pour la comparaison)
  const filteredArticles = blogArticles.filter((article) => normalizeSlug(article.category) === normalizedCategory)

  // Pagination
  const articlesPerPage = 6
  const indexOfLastArticle = currentPage * articlesPerPage
  const indexOfFirstArticle = indexOfLastArticle - articlesPerPage
  const currentArticles = filteredArticles.slice(indexOfFirstArticle, indexOfLastArticle)
  const totalPages = Math.ceil(filteredArticles.length / articlesPerPage)

  // Extraire toutes les catégories uniques des vrais articles
  const categories = [...new Set(blogArticles.map((article) => article.category))].sort()

  return (
    <>
      <PageHeader
        title={`Articles sur ${displayName}`}
        description={`Découvrez nos conseils d'experts et actualités sur ${displayName.toLowerCase()}`}
        backgroundImage="/modern-apartment-living.png"
        breadcrumbs={[
          { label: "Accueil", href: "/" },
          { label: "Blog", href: "/blog" },
          { label: displayName, href: `/blog/categories/${normalizedCategory}` },
        ]}
      />

      <BlogLayout categories={categories} currentCategory={displayName}>
        <div className="mb-6">
          <h2 className="text-2xl font-bold mb-4">
            {filteredArticles.length} article{filteredArticles.length > 1 ? "s" : ""} dans la catégorie "{displayName}"
          </h2>
        </div>

        {filteredArticles.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {currentArticles.map((article) => {
              // S'assurer que l'image n'est jamais une chaîne vide
              const imageUrl = article.image || "/default-article-image.png"

              return (
                <div
                  key={article.slug}
                  className="bg-white rounded-lg shadow-sm overflow-hidden border border-gray-100"
                >
                  <Link href={`/blog/articles/${article.slug}`}>
                    <div className="relative h-48">
                      <SafeImage src={imageUrl} alt={`Image pour ${article.title}`} fill className="object-cover" />
                      <div className="absolute top-2 right-2 bg-blue-600 text-white text-xs px-2 py-1 rounded">
                        {article.category}
                      </div>
                    </div>
                  </Link>
                  <div className="p-4">
                    <Link href={`/blog/articles/${article.slug}`}>
                      <h3 className="text-lg font-bold mb-2 hover:text-blue-600 transition-colors line-clamp-2">
                        {article.title}
                      </h3>
                    </Link>
                    <p className="text-gray-600 text-sm mb-3 line-clamp-3">{article.description}</p>
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-gray-500">{formatDate(article.date)}</span>
                      <Link
                        href={`/blog/articles/${article.slug}`}
                        className="text-blue-600 hover:underline text-sm font-medium"
                      >
                        Lire l'article →
                      </Link>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        ) : (
          <div className="bg-gray-50 p-8 rounded-lg text-center">
            <h3 className="text-xl font-semibold mb-2">Aucun article trouvé</h3>
            <p className="text-gray-600 mb-4">
              Il n'y a pas encore d'articles dans cette catégorie. Revenez bientôt pour découvrir nos nouveaux contenus.
            </p>
            <Link href="/blog" className="text-blue-600 hover:underline">
              Retourner à tous les articles
            </Link>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-8 flex justify-center">
            <nav className="inline-flex rounded-md shadow-sm">
              <Link
                href={`/blog/categories/${normalizedCategory}?page=${Math.max(1, currentPage - 1)}`}
                className={`px-4 py-2 border border-gray-300 rounded-l-md text-sm font-medium ${
                  currentPage === 1
                    ? "bg-gray-100 text-gray-400 cursor-not-allowed"
                    : "bg-white text-gray-700 hover:bg-gray-50"
                }`}
              >
                Précédent
              </Link>

              {Array.from({ length: totalPages }, (_, i) => i + 1).map((pageNumber) => (
                <Link
                  key={pageNumber}
                  href={`/blog/categories/${normalizedCategory}?page=${pageNumber}`}
                  className={`px-4 py-2 border-t border-b border-r border-gray-300 text-sm font-medium ${
                    currentPage === pageNumber
                      ? "bg-blue-600 text-white hover:bg-blue-700"
                      : "bg-white text-gray-700 hover:bg-gray-50"
                  }`}
                >
                  {pageNumber}
                </Link>
              ))}

              <Link
                href={`/blog/categories/${normalizedCategory}?page=${Math.min(totalPages, currentPage + 1)}`}
                className={`px-4 py-2 border border-gray-300 rounded-r-md text-sm font-medium ${
                  currentPage === totalPages
                    ? "bg-gray-100 text-gray-400 cursor-not-allowed"
                    : "bg-white text-gray-700 hover:bg-gray-50"
                }`}
              >
                Suivant
              </Link>
            </nav>
          </div>
        )}
      </BlogLayout>
    </>
  )
}
