"use client";

import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import Fuse from "fuse.js";
import { useSearchParams } from "next/navigation";
import { IconSearch, IconX } from "@tabler/icons-react";
import Image from "next/image";
import Link from "next/link";
import { Input } from "@/components/ui/input";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
  PaginationEllipsis,
} from "@/components/ui/pagination";

const POSTS_PER_PAGE = 15;

interface BlogPost {
  title: string;
  slug: string;
  category: string;
  image: string;
  description: string;
  date: string;
  author: string;
  authorAvatar: string;
  readingTime: number;
  keywords?: string[];
  topics?: string[];
}

interface BlogGridProps {
  posts: BlogPost[];
}

// Category labels in French
const CATEGORY_LABELS: Record<string, string> = {
  actualites: "Actualités",
  guides: "Guides",
  reglementation: "Réglementation",
  "cas-clients": "Cas clients",
};

export function BlogGrid({ posts }: BlogGridProps) {
  const searchParams = useSearchParams();
  const initialQuery = searchParams.get("q") ?? "";
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState(initialQuery);
  const [currentPage, setCurrentPage] = useState(1);
  const searchInputRef = useRef<HTMLInputElement>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);

  // Sync URL ?q= param on mount
  useEffect(() => {
    if (initialQuery && searchInputRef.current) {
      searchInputRef.current.value = initialQuery;
    }
  }, [initialQuery]);

  // Fuse.js search index
  const fuse = useMemo(
    () =>
      new Fuse(posts, {
        keys: [
          { name: "title", weight: 0.4 },
          { name: "description", weight: 0.3 },
          { name: "keywords", weight: 0.2 },
          { name: "topics", weight: 0.1 },
        ],
        threshold: 0.3,
        ignoreLocation: true,
      }),
    [posts],
  );

  // Extract unique categories dynamically from posts
  const categories = useMemo(() => {
    const uniqueCategories = [...new Set(posts.map((post) => post.category))];
    return uniqueCategories.sort();
  }, [posts]);

  // Filter: search first, then category
  const filteredPosts = useMemo(() => {
    let results = posts;

    if (searchQuery.trim().length >= 2) {
      results = fuse.search(searchQuery).map((r) => r.item);
    }

    if (selectedCategory) {
      results = results.filter((post) => post.category === selectedCategory);
    }

    return results;
  }, [posts, searchQuery, selectedCategory, fuse]);

  // Pagination
  const totalPages = Math.ceil(filteredPosts.length / POSTS_PER_PAGE);
  const paginatedPosts = useMemo(() => {
    const start = (currentPage - 1) * POSTS_PER_PAGE;
    return filteredPosts.slice(start, start + POSTS_PER_PAGE);
  }, [filteredPosts, currentPage]);

  // Reset page when category or search changes
  const handleCategoryChange = (category: string | null) => {
    setSelectedCategory(category);
    setCurrentPage(1);
  };

  const handleSearchChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      if (debounceRef.current) clearTimeout(debounceRef.current);
      debounceRef.current = setTimeout(() => {
        setSearchQuery(value);
        setCurrentPage(1);
      }, 300);
    },
    [],
  );

  const clearSearch = useCallback(() => {
    setSearchQuery("");
    setCurrentPage(1);
    if (searchInputRef.current) searchInputRef.current.value = "";
  }, []);

  // Count posts per category
  const categoryCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    posts.forEach((post) => {
      counts[post.category] = (counts[post.category] || 0) + 1;
    });
    return counts;
  }, [posts]);

  return (
    <section className="py-16 lg:py-24 bg-gray-50">
      <div className="container mx-auto px-4">
        {/* Section Header */}
        <div className="text-center mb-10">
          <h2 className="text-2xl md:text-3xl lg:text-4xl font-bold text-gray-900 mb-4">
            Explorez nos articles
          </h2>
          <p className="text-gray-600 max-w-2xl mx-auto">
            Recherchez ou filtrez par catégorie pour trouver les contenus qui vous intéressent
          </p>
        </div>

        {/* Search Bar */}
        <div className="max-w-xl mx-auto mb-8">
          <div className="relative">
            <IconSearch className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
            <Input
              ref={searchInputRef}
              type="search"
              placeholder="Rechercher un article (TURPE, courtier, PME...)"
              onChange={handleSearchChange}
              className="pl-10 pr-10 h-12 rounded-full bg-white border-gray-200 shadow-sm text-base focus-visible:ring-orange-500"
              aria-label="Rechercher un article"
            />
            {searchQuery && (
              <button
                onClick={clearSearch}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                aria-label="Effacer la recherche"
              >
                <IconX className="w-5 h-5" />
              </button>
            )}
          </div>
          {searchQuery.trim().length >= 2 && (
            <p className="text-center text-sm text-gray-500 mt-2">
              {filteredPosts.length} résultat{filteredPosts.length !== 1 ? "s" : ""} pour &quot;{searchQuery}&quot;
            </p>
          )}
        </div>

        {/* Category Filters */}
        <div className="flex flex-wrap justify-center gap-3 mb-12">
          {/* All button */}
          <button
            onClick={() => handleCategoryChange(null)}
            aria-current={selectedCategory === null ? "true" : undefined}
            className={`px-5 py-2.5 rounded-full text-sm font-medium transition-all duration-300 ${
              selectedCategory === null
                ? "bg-orange-500 text-white shadow-lg shadow-orange-500/30"
                : "bg-white text-gray-700 hover:bg-gray-100 shadow-sm"
            }`}
          >
            Tous
            <span className="ml-2 text-xs opacity-80" aria-hidden="true">
              ({posts.length})
            </span>
          </button>

          {/* Category buttons */}
          {categories.map((category) => (
            <button
              key={category}
              onClick={() => handleCategoryChange(category)}
              aria-current={selectedCategory === category ? "true" : undefined}
              className={`px-5 py-2.5 rounded-full text-sm font-medium transition-all duration-300 ${
                selectedCategory === category
                  ? "bg-orange-500 text-white shadow-lg shadow-orange-500/30"
                  : "bg-white text-gray-700 hover:bg-gray-100 shadow-sm"
              }`}
            >
              {CATEGORY_LABELS[category] || category}
              <span className="ml-2 text-xs opacity-80" aria-hidden="true">
                ({categoryCounts[category] || 0})
              </span>
            </button>
          ))}
        </div>

        {/* Blog Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {paginatedPosts.map((post, index) => (
            <article
              key={post.slug}
              className="group bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-xl transition-all duration-500 ease-out"
              style={{
                animationDelay: `${index * 100}ms`,
              }}
            >
              <Link href={`/${post.category}/${post.slug}`} scroll={true} className="block">
                {/* Image */}
                <div className="relative h-52 overflow-hidden">
                  <Image
                    src={post.image}
                    alt={post.title}
                    fill
                    sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                    className="object-cover transition-transform duration-500 group-hover:scale-105"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />

                  {/* Category Badge */}
                  <span className="absolute top-4 left-4 px-3 py-1 text-xs font-bold text-white bg-orange-500/90 rounded-full uppercase tracking-wide">
                    {CATEGORY_LABELS[post.category] || post.category}
                  </span>
                </div>

                {/* Content */}
                <div className="p-6">
                  <h3 className="text-lg font-bold text-gray-900 mb-2 line-clamp-2 group-hover:text-orange-700 transition-colors duration-300">
                    {post.title}
                  </h3>
                  <p className="text-sm text-gray-600 line-clamp-2 mb-4">
                    {post.description}
                  </p>

                  {/* Meta */}
                  <div className="flex items-center justify-between text-xs text-gray-600">
                    <div className="flex items-center gap-2">
                      <Image
                        src={post.authorAvatar}
                        alt={post.author}
                        width={40}
                        height={40}
                        className="h-6 w-6 md:h-8 md:w-8 rounded-full object-cover"
                      />
                      <span>{post.author}</span>
                    </div>
                    <time dateTime={post.date}>
                      {format(new Date(post.date), "d MMM yyyy", { locale: fr })}
                    </time>
                  </div>
                </div>
              </Link>
            </article>
          ))}
        </div>

        {/* Empty State */}
        {filteredPosts.length === 0 && (
          <div className="text-center py-16">
            <p className="text-gray-500 text-lg">
              {searchQuery
                ? `Aucun article trouvé pour "${searchQuery}".`
                : "Aucun article trouvé dans cette catégorie."}
            </p>
            {searchQuery && (
              <button
                onClick={clearSearch}
                className="mt-4 text-orange-700 hover:text-orange-700 font-medium"
              >
                Effacer la recherche
              </button>
            )}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-12">
            <Pagination>
              <PaginationContent>
                {currentPage > 1 && (
                  <PaginationItem>
                    <PaginationPrevious
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        setCurrentPage((p) => Math.max(1, p - 1));
                        window.scrollTo({ top: 0, behavior: "smooth" });
                      }}
                    />
                  </PaginationItem>
                )}

                {Array.from({ length: totalPages }, (_, i) => i + 1).map(
                  (page) => {
                    if (
                      page === 1 ||
                      page === totalPages ||
                      Math.abs(page - currentPage) <= 1
                    ) {
                      return (
                        <PaginationItem key={page}>
                          <PaginationLink
                            href="#"
                            isActive={page === currentPage}
                            onClick={(e) => {
                              e.preventDefault();
                              setCurrentPage(page);
                              window.scrollTo({ top: 0, behavior: "smooth" });
                            }}
                          >
                            {page}
                          </PaginationLink>
                        </PaginationItem>
                      );
                    }
                    if (
                      page === 2 && currentPage > 3 ||
                      page === totalPages - 1 && currentPage < totalPages - 2
                    ) {
                      return (
                        <PaginationItem key={page}>
                          <PaginationEllipsis />
                        </PaginationItem>
                      );
                    }
                    return null;
                  },
                )}

                {currentPage < totalPages && (
                  <PaginationItem>
                    <PaginationNext
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        setCurrentPage((p) => Math.min(totalPages, p + 1));
                        window.scrollTo({ top: 0, behavior: "smooth" });
                      }}
                    />
                  </PaginationItem>
                )}
              </PaginationContent>
            </Pagination>
            <p className="text-center text-sm text-gray-500 mt-4">
              {filteredPosts.length} article{filteredPosts.length > 1 ? "s" : ""} — Page {currentPage} sur {totalPages}
            </p>
          </div>
        )}
      </div>
    </section>
  );
}
