"use client";

import { useState, useEffect } from "react";
import { Calendar, ArrowRight, Tag, Clock, Search, ChevronLeft, ChevronRight } from "lucide-react";

type Article = {
  id: string;
  title: string;
  slug: string;
  excerpt: string;
  image: string;
  category: string;
  categoryColor: string;
  featured: boolean;
  publishedAt: string | null;
};

const CATEGORIES = ["Tous", "Projet", "Rapport", "Événement", "Partenariat"];

export default function ActualitesPage() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("Tous");
  const [currentPage, setCurrentPage] = useState(1);
  const articlesPerPage = 4;

  useEffect(() => {
    fetch("/api/articles")
      .then((res) => res.json())
      .then((data) => {
        setArticles(data);
        setLoading(false);
      })
      .catch((error) => {
        console.error("Error fetching articles:", error);
        setLoading(false);
      });
  }, []);

  const formatDate = (dateString: string | null) => {
    if (!dateString) return "";
    const date = new Date(dateString);
    return new Intl.DateTimeFormat("fr-FR", {
      day: "numeric",
      month: "long",
      year: "numeric",
    }).format(date);
  };

  // Filter articles
  const filteredArticles = articles.filter(article => {
    const matchesSearch = article.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         article.excerpt.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory === "Tous" || article.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const featuredArticle = filteredArticles.find(article => article.featured);
  const regularArticles = filteredArticles.filter(article => !article.featured);

  // Pagination
  const totalPages = Math.ceil(regularArticles.length / articlesPerPage);
  const startIndex = (currentPage - 1) * articlesPerPage;
  const paginatedArticles = regularArticles.slice(startIndex, startIndex + articlesPerPage);

  return (
    <>
      {/* Page Hero */}
      <section className="relative bg-linear-to-br from-[#F7F8F5] via-white to-[#E8F5E9] py-20 sm:py-28 overflow-hidden">
        {/* Background Pattern */}
        <div className="absolute inset-0 opacity-[0.03]">
          <div className="absolute inset-0" style={{
            backgroundImage: `radial-gradient(circle at 2px 2px, #4A7C59 1px, transparent 0)`,
            backgroundSize: '32px 32px'
          }}></div>
        </div>

        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
          <p className="text-xs font-semibold text-[#4A7C59] uppercase tracking-widest mb-4">Restez informé</p>
          <h1 className="font-serif text-4xl sm:text-5xl lg:text-6xl font-black text-[#2C3E50] leading-tight mb-6">
            Actualités
          </h1>
          <p className="text-lg sm:text-xl text-gray-600 leading-relaxed max-w-3xl mb-8">
            Découvrez nos dernières nouvelles, projets, rapports de terrain et événements. Suivez l'impact de nos interventions en Mauritanie.
          </p>

          {/* Search & Filter */}
          <div className="flex flex-col md:flex-row gap-4 max-w-4xl">
            {/* Search Bar */}
            <div className="flex-1 relative">
              <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder="Rechercher un article..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-12 pr-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:outline-none focus:border-[#4A7C59] transition-colors text-sm"
              />
            </div>

            {/* Category Filter */}
            <div className="flex gap-2 overflow-x-auto pb-2 md:pb-0">
              {CATEGORIES.map((category) => (
                <button
                  key={category}
                  onClick={() => {
                    setSelectedCategory(category);
                    setCurrentPage(1);
                  }}
                  className={`px-4 py-3 rounded-lg text-xs font-semibold whitespace-nowrap transition-all ${
                    selectedCategory === category
                      ? "bg-[#4A7C59] text-white shadow-md"
                      : "bg-white text-gray-700 border-2 border-gray-200 hover:border-[#4A7C59]"
                  }`}
                >
                  {category}
                </button>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Featured Article */}
      {loading ? (
        <section className="py-12 bg-white border-b border-gray-100">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="animate-pulse">
              <div className="h-6 bg-gray-200 rounded w-24 mb-6"></div>
              <div className="bg-gray-100 rounded-2xl h-96"></div>
            </div>
          </div>
        </section>
      ) : featuredArticle ? (
        <section className="py-12 bg-white border-b border-gray-100">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
            <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-6 flex items-center gap-2">
              <Tag size={12} />
              À la une
            </p>

            <article className="group bg-white rounded-2xl border-2 border-gray-200 overflow-hidden hover:border-[#4A7C59]/30 hover:shadow-2xl transition-all duration-300">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-0">
                {/* Image */}
                <div className="relative h-80 lg:h-auto overflow-hidden bg-gray-100">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={featuredArticle.image}
                    alt={featuredArticle.title}
                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent" />

                  {/* Category Badge */}
                  <span
                    className="absolute top-6 left-6 text-xs font-bold text-white px-3 py-1.5 rounded-lg shadow-lg"
                    style={{ backgroundColor: featuredArticle.categoryColor }}
                  >
                    {featuredArticle.category}
                  </span>
                </div>

                {/* Content */}
                <div className="p-8 lg:p-10 flex flex-col justify-center">
                  <div className="flex items-center gap-4 text-xs text-gray-500 mb-4">
                    <span className="flex items-center gap-1.5">
                      <Calendar size={14} className="text-[#4A7C59]" />
                      {formatDate(featuredArticle.publishedAt)}
                    </span>
                    <span className="flex items-center gap-1.5">
                      <Clock size={14} className="text-[#4A7C59]" />
                      5 min de lecture
                    </span>
                  </div>

                  <h2 className="font-serif text-2xl sm:text-3xl font-bold text-[#2C3E50] mb-4 leading-tight group-hover:text-[#4A7C59] transition-colors">
                    {featuredArticle.title}
                  </h2>

                  <p className="text-gray-800 leading-relaxed mb-6 font-medium">
                    {featuredArticle.excerpt}
                  </p>

                  <a
                    href={`/actualites/${featuredArticle.slug}`}
                    className="inline-flex items-center gap-2 text-[#4A7C59] hover:text-[#3d6849] font-semibold transition-colors group/link"
                  >
                    Lire la suite
                    <ArrowRight size={16} className="group-hover/link:translate-x-1 transition-transform" />
                  </a>
                </div>
              </div>
            </article>
          </div>
        </section>
      ) : null}

      {/* Regular Articles Grid */}
      <section className="py-16 bg-white">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              {[1, 2, 3, 4].map((i) => (
                <div key={i} className="animate-pulse">
                  <div className="bg-gray-200 rounded-2xl h-56 mb-4"></div>
                  <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
                  <div className="h-4 bg-gray-200 rounded w-full"></div>
                </div>
              ))}
            </div>
          ) : paginatedArticles.length > 0 ? (
            <>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                {paginatedArticles.map((article) => (
              <article
                key={article.id}
                className="group bg-white rounded-2xl border-2 border-gray-200 overflow-hidden hover:border-[#4A7C59]/30 hover:shadow-xl transition-all duration-300"
              >
                {/* Image */}
                <div className="relative h-56 overflow-hidden bg-gray-100">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={article.image}
                    alt={article.title}
                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent" />

                  {/* Category Badge */}
                  <span
                    className="absolute top-4 left-4 text-xs font-bold text-white px-3 py-1.5 rounded-lg shadow-lg"
                    style={{ backgroundColor: article.categoryColor }}
                  >
                    {article.category}
                  </span>
                </div>

                {/* Content */}
                <div className="p-6">
                  <div className="flex items-center gap-3 text-xs text-gray-500 mb-3">
                    <span className="flex items-center gap-1.5">
                      <Calendar size={12} className="text-[#4A7C59]" />
                      {formatDate(article.publishedAt)}
                    </span>
                  </div>

                  <h3 className="font-serif text-xl font-bold text-[#2C3E50] mb-3 leading-tight group-hover:text-[#4A7C59] transition-colors">
                    {article.title}
                  </h3>

                  <p className="text-sm text-gray-800 leading-relaxed mb-4 font-semibold">
                    {article.excerpt}
                  </p>

                  <a
                    href={`/actualites/${article.slug}`}
                    className="inline-flex items-center gap-2 text-sm text-[#4A7C59] hover:text-[#3d6849] font-semibold transition-colors group/link"
                  >
                    Lire la suite
                    <ArrowRight size={14} className="group-hover/link:translate-x-1 transition-transform" />
                  </a>
                </div>
              </article>
                ))}
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-center gap-2 mt-12">
                  <button
                    onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                    disabled={currentPage === 1}
                    className="p-2 rounded-lg border-2 border-gray-200 hover:border-[#4A7C59] hover:bg-[#4A7C59] hover:text-white transition-all disabled:opacity-30 disabled:cursor-not-allowed"
                    aria-label="Page précédente"
                  >
                    <ChevronLeft size={20} />
                  </button>

                  <div className="flex gap-2">
                    {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`w-10 h-10 rounded-lg font-semibold transition-all ${
                          currentPage === page
                            ? "bg-[#4A7C59] text-white shadow-md"
                            : "border-2 border-gray-200 text-gray-700 hover:border-[#4A7C59]"
                        }`}
                      >
                        {page}
                      </button>
                    ))}
                  </div>

                  <button
                    onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                    disabled={currentPage === totalPages}
                    className="p-2 rounded-lg border-2 border-gray-200 hover:border-[#4A7C59] hover:bg-[#4A7C59] hover:text-white transition-all disabled:opacity-30 disabled:cursor-not-allowed"
                    aria-label="Page suivante"
                  >
                    <ChevronRight size={20} />
                  </button>
                </div>
              )}
            </>
          ) : (
            <div className="text-center py-12">
              <p className="text-gray-500 text-lg">Aucun article trouvé pour cette recherche.</p>
            </div>
          )}
        </div>
      </section>
    </>
  );
}
