"use client";
import React, { useEffect, useState } from "react";
import ArticleCard from "@/components/ArticleCard";

const sortOptions = [
  { value: "1", label: "Du plus récent" },
  { value: "2", label: "Du moins récent" },
  { value: "3", label: "Du plus populaire" },
];

type ArticleTag = {
  id: number;
  name: string;
};

type Article = {
  id?: number;
  title: string;
  content: string;
  tags: ArticleTag[];
  description?: string;
  date_creation: Date;
  updatedAt: string;
  image: {
    path: string;
  };
  author?: {
    id?: number;
    name?: string;
    email?: string;
    image?: string;
  };
};

export default function ListArticles() {
  const [search, setSearch] = useState("");
  const [sortBy, setSortBy] = useState("1");
  const [articles, setArticles] = useState<Article[]>([]);
  const [initialArticles, setInitialArticles] = useState<Article[]>([]);

  useEffect(() => {
    async function fetchArticles() {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || "";
        const res = await fetch(`${apiUrl}/api/articles?published=true`, {
          credentials: "include",
        });
        if (!res.ok) throw new Error("Erreur lors de la récupération des articles");
        const data = await res.json();
        setArticles(data);
        setInitialArticles(data);
      } catch (err) {
        console.error("Erreur fetch articles:", err);
        setArticles([]);
        setInitialArticles([]);
      }
    }
    fetchArticles();
  }, []);

  const [showCount, setShowCount] = useState(6);

  useEffect(() => {
    let filtered = initialArticles.filter(
      (a) =>
        a.title.toLowerCase().includes(search.toLowerCase()) ||
        a.tags.map(tag => tag.name).join(" ").toLowerCase().includes(search.toLowerCase()),
    );
    if (sortBy === "2") filtered = filtered.slice().reverse();
    setArticles(filtered);
  }, [search, sortBy, initialArticles]);

  return (
    <section className="flex flex-col md:flex-row gap-8 w-full mx-auto py-8 px-[5dvw]">
      <div className="flex-1">
        <div className="flex flex-col md:flex-row items-center gap-4 mb-6">
          <input
            type="search"
            id="search_box"
            placeholder="Recherchez par mots clefs ou par tags"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full md:w-2/3 px-4 py-2 h-12 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-400"
          />
          <div className="w-full md:w-1/3">
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="w-full px-3 h-12 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-400"
            >
              {sortOptions.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
        </div>
        <div
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6"
          id="article_list_container"
        >
          {articles.length === 0 ? (
            <em>
              <h3 className="mb-2 text-lg text-gray-500">
                Aucun élément ne correspond à votre recherche...
              </h3>
            </em>
          ) : (
            <>
              {articles.slice(0, showCount).map((article, idx) => (
                <ArticleCard
                  article={article}
                  key={
                    article.id !== undefined
                      ? String(article.id)
                      : `article-${idx}`
                  }
                />
              ))}
              {articles.length > showCount && (
                <div className="col-span-full flex justify-center mt-4">
                  <button
                    onClick={() => setShowCount((c) => c + 6)}
                    className="px-6 py-2 bg-primary text-white border-primary border-2 rounded hover:bg-white hover:text-primary cursor-pointer transition"
                  >
                    Afficher plus
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </section>
  );
}
