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

export const metadata: Metadata = {
  title: "Recherche d'articles | Blog DOGES",
  description: "Recherchez parmi nos articles d'experts sur la gestion locative et l'immobilier.",
  alternates: {
    canonical: "https://www.dogesadb.fr/blog/search",
  },
}

// Fonction utilitaire pour formater les dates de manière cohérente
function formatDate(dateString: string): string {
  const options: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "long",
    day: "numeric",
  }
  return new Date(dateString).toLocaleDateString("fr-FR", options)
}

export default function SearchPage({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  const query = typeof searchParams.q === "string" ? searchParams.q.toLowerCase() : ""
  const currentPage = typeof searchParams.page === "string" ? Number.parseInt(searchParams.page) : 1

  // Recherche dans les articles nettoyés de blog-utils.ts
  const searchResults = query
    ? blogArticles.filter(
        (article) =>
          article.title.toLowerCase().includes(query) ||
          article.description.toLowerCase().includes(query) ||
          article.category.toLowerCase().includes(query),
      )
    : []

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

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

  return (
    <>
      <PageHeader
        title="Recherche d'articles"
        description="Trouvez les informations dont vous avez besoin"
        backgroundImage="/modern-apartment-living.png"
      />

      <BlogLayout categories={categories}>
        <div className="mb-6">
          <form className="relative mb-8">
            <input
              type="text"
              placeholder="Rechercher un article..."
              defaultValue={query}
              name="q"
              className="w-full p-3 pl-10 border rounded-lg"
            />
            <Search className="absolute left-3 top-3.5 h-5 w-5 text-gray-400" />
            <button
              type="submit"
              className="absolute right-3 top-2 px-4 py-1 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              Rechercher
            </button>
          </form>

          {query ? (
            <h2 className="text-2xl font-bold mb-4">
              {searchResults.length} résultat{searchResults.length !== 1 ? "s" : ""} pour "{query}"
            </h2>
          ) : (
            <h2 className="text-2xl font-bold mb-4">Veuillez saisir un terme de recherche</h2>
          )}
        </div>

        {query && searchResults.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {currentArticles.map((article) => (
              <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={article.image} 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>
        ) : query ? (
          <div className="bg-gray-50 p-8 rounded-lg text-center">
            <h3 className="text-xl font-semibold mb-2">Aucun résultat trouvé</h3>
            <p className="text-gray-600 mb-4">
              Nous n'avons pas trouvé d'articles correspondant à votre recherche. Essayez avec d'autres mots-clés.
            </p>
            <Link href="/blog" className="text-blue-600 hover:underline">
              Voir tous les articles
            </Link>
          </div>
        ) : (
          <div className="bg-gray-50 p-8 rounded-lg text-center">
            <h3 className="text-xl font-semibold mb-2">Commencez votre recherche</h3>
            <p className="text-gray-600 mb-4">
              Utilisez la barre de recherche ci-dessus pour trouver des articles sur les sujets qui vous intéressent.
            </p>
            <Link href="/blog" className="text-blue-600 hover:underline">
              Parcourir tous les articles
            </Link>
          </div>
        )}

        {/* Pagination */}
        {query && totalPages > 1 && (
          <div className="mt-8 flex justify-center">
            <nav className="inline-flex rounded-md shadow-sm">
              <Link
                href={`/blog/search?q=${encodeURIComponent(query)}&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/search?q=${encodeURIComponent(query)}&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/search?q=${encodeURIComponent(query)}&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>
    </>
  )
}
