import Link from "next/link"
import type { Metadata } from "next"
import PageHeader from "@/components/page-header"
import { SafeImage } from "@/components/safe-image"
import BlogLayout from "@/components/blog-layout"
import { Filter } from "lucide-react"
import { blogArticles } from "@/lib/blog-utils"
import { getArticleImage } from "@/lib/blog-images"

// 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)
}

export const metadata: Metadata = {
  title: "Blog DOGES | Conseils et actualités en gestion immobilière",
  description:
    "Découvrez nos articles d'experts sur la gestion locative, l'investissement immobilier et les conseils pour propriétaires bailleurs à Paris et en Île-de-France.",
  alternates: {
    canonical: "https://www.dogesadb.fr/blog",
  },
}

// 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)
}

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

export default function BlogPage({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  // Récupérer la page actuelle depuis les paramètres d'URL
  const currentPage = typeof searchParams.page === "string" ? Number.parseInt(searchParams.page) : 1
  const currentCategory = typeof searchParams.category === "string" ? searchParams.category : undefined

  // Filtrer les articles par catégorie si nécessaire
  const filteredArticles = currentCategory
    ? blogArticles.filter((article) => normalizeSlug(article.category) === normalizeSlug(currentCategory))
    : blogArticles

  // 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)

  return (
    <>
      <PageHeader
        title="Blog DOGES"
        description="Conseils d'experts et actualités en gestion immobilière"
        backgroundImage="/modern-apartment-living.png"
        breadcrumbs={[{ label: "Blog", href: "/blog" }]}
      />

      <BlogLayout categories={categories} currentCategory={currentCategory}>
        <div className="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center">
          <h2 className="text-2xl font-bold mb-4 sm:mb-0">
            {currentCategory ? `Articles dans la catégorie "${currentCategory}"` : "Tous les articles"}
          </h2>
          <div className="flex items-center gap-2">
            <div className="relative">
              <select className="pl-8 pr-4 py-2 border rounded-md appearance-none bg-white text-sm">
                <option value="">Trier par date</option>
                <option value="asc">Plus anciens d'abord</option>
                <option value="desc">Plus récents d'abord</option>
              </select>
              <Filter className="absolute left-2 top-2.5 h-4 w-4 text-gray-400" />
            </div>
          </div>
        </div>

        <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 || getArticleImage(article.slug) || "/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>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-8 flex justify-center">
            <nav className="inline-flex rounded-md shadow-sm">
              <Link
                href={`/blog?page=${Math.max(1, currentPage - 1)}${
                  currentCategory ? `&category=${normalizeSlug(currentCategory)}` : ""
                }`}
                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?page=${pageNumber}${currentCategory ? `&category=${normalizeSlug(currentCategory)}` : ""}`}
                  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?page=${Math.min(totalPages, currentPage + 1)}${
                  currentCategory ? `&category=${normalizeSlug(currentCategory)}` : ""
                }`}
                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>
    </>
  )
}
