import { fetchBlogPosts } from "@/lib/blog-api";
import BlogHeader from "@/components/blog/blog-header";
import BlogPostCard from "@/components/blog/blog-post-card";

export const metadata = {
  title: "Blog Archive - ElectroPro",
  description:
    "Browse our complete collection of articles, news, and insights about electrical products and industry trends.",
};

export default async function BlogArchivePage() {
  const posts = await fetchBlogPosts();

  const groupedPosts: Record<string, typeof posts> = {};

  posts.forEach((post) => {
    const date = new Date(post.date);
    const year = date.getFullYear();
    const month = date.toLocaleString("default", { month: "long" });
    const key = `${year}-${month}`;

    if (!groupedPosts[key]) {
      groupedPosts[key] = [];
    }

    groupedPosts[key].push(post);
  });

  const sortedKeys = Object.keys(groupedPosts).sort((a, b) => {
    const [yearA, monthA] = a.split("-");
    const [yearB, monthB] = b.split("-");
    return Number(yearB) - Number(yearA) || monthB.localeCompare(monthA);
  });

  return (
    <div className="bg-white min-h-screen px-4 md:px-8">
      <BlogHeader />

      <div className="container max-w-7xl mx-auto py-12">
        <div className="">
          <h1 className="text-4xl font-bold text-gray-900 mb-6">
            Blog Archive
          </h1>
          <p className="text-xl text-gray-600 mb-12">
            Browse our complete collection of articles, news, and insights about
            electrical products and industry trends.
          </p>

          <div className="space-y-16">
            {sortedKeys.map((key) => {
              const [year, month] = key.split("-");
              const posts = groupedPosts[key];

              return (
                <section key={key}>
                  <h2 className="text-2xl font-bold text-gray-900 mb-6 flex items-center">
                    <span className="w-6 h-1 bg-red-600 mr-3"></span>
                    {month} {year}
                  </h2>

                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    {posts.map((post) => (
                      <BlogPostCard key={post.id} post={post} />
                    ))}
                  </div>
                </section>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
