"use client";
import { useEffect, useState } from "react";
import Image from "next/image";
import { getListArticle } from "@/service/article";

// Type dari API
type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  createdByName: string;
  thumbnailUrl: string;
  categories: { title: string }[];
  files: { file_url: string; file_alt: string }[];
};

export default function News() {
  const [articlesByCategory, setArticlesByCategory] = useState<
    Record<string, Article[]>
  >({});
  const [loading, setLoading] = useState(true);
  const [visiblePosts, setVisiblePosts] = useState<Record<string, number>>({});

  useEffect(() => {
    fetchArticles();
  }, []);

  async function fetchArticles() {
    try {
      const req = {
        limit: "20", // ambil lebih banyak, nanti dibagi per kategori
        page: 1,
        search: "",
        categorySlug: "",
        sort: "desc",
        isPublish: true,
        sortBy: "created_at",
      };

      const res = await getListArticle(req);
      const allArticles: Article[] = res?.data?.data || [];

      // Group by category
      const grouped: Record<string, Article[]> = {};
      allArticles.forEach((a) => {
        const cat = a.categoryName || a.categories?.[0]?.title || "Lainnya";
        if (!grouped[cat]) grouped[cat] = [];
        grouped[cat].push(a);
      });

      setArticlesByCategory(grouped);

      // Set default visiblePosts untuk setiap kategori
      const initialVisible: Record<string, number> = {};
      Object.keys(grouped).forEach((cat) => {
        initialVisible[cat] = 2; // awal 2 post bawah
      });
      setVisiblePosts(initialVisible);
    } catch (error) {
      console.error("Gagal ambil artikel:", error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
      {loading && <p className="text-center">Memuat data...</p>}

      {!loading &&
        Object.keys(articlesByCategory).map((category) => {
          const posts = articlesByCategory[category];
          if (!posts?.length) return null;

          const postsTop = posts.slice(0, 2); // 2 atas
          const postsBottom = posts.slice(2); // sisanya

          return (
            <div key={category} className="border p-4 bg-white">
              {/* Header kategori */}
              <div className="bg-[#3677A8] text-white px-3 py-1 text-sm font-bold inline-block mb-4">
                {category}
              </div>

              {/* Posts atas */}
              {postsTop.map((post) => (
                <PostItem key={post.id} post={post} />
              ))}

              {/* Banner Kolom PPS */}
              <div className="relative mb-2 h-[120px] overflow-hidden flex items-center border my-8">
                <Image
                  src={"/image-kolom.png"}
                  alt="Kolom PPS"
                  fill
                  className="w-full object-cover"
                />
              </div>

              {/* Posts bawah (pakai visiblePosts[category]) */}
              {postsBottom.slice(0, visiblePosts[category] || 2).map((post) => (
                <PostItem key={post.id} post={post} />
              ))}

              {/* Tombol Load More */}
              {(visiblePosts[category] || 2) < postsBottom.length && (
                <div className="flex justify-center">
                  <button
                    onClick={() =>
                      setVisiblePosts((prev) => ({
                        ...prev,
                        [category]: (prev[category] || 2) + 2,
                      }))
                    }
                    className="bg-black text-white text-xs px-4 py-2 hover:bg-gray-800 mt-4"
                  >
                    LOAD MORE POSTS
                  </button>
                </div>
              )}
            </div>
          );
        })}
    </div>
  );
}

function PostItem({ post }: { post: Article }) {
  return (
    <div className="flex gap-4 mb-6 pb-4">
      {/* Gambar */}
      <div className="relative w-40 h-28 flex-shrink-0">
        <Image
          src={
            post.thumbnailUrl || post.files?.[0]?.file_url || "/placeholder.jpg"
          }
          alt={post.files?.[0]?.file_alt || post.title}
          fill
          className="object-cover"
        />
      </div>

      {/* Konten */}
      <div className="flex flex-col justify-between">
        <div>
          <h2 className="font-semibold text-lg mb-1 hover:text-[#3677A8] cursor-pointer">
            {post.title}
          </h2>
          <p className="text-xs text-gray-500 mb-1">
            by {post.createdByName} •{" "}
            {new Date(post.createdAt).toLocaleDateString("id-ID", {
              day: "numeric",
              month: "long",
              year: "numeric",
            })}{" "}
            • 💬 0
          </p>
          <p className="text-sm text-gray-600 mb-2 line-clamp-2">
            {post.description}
          </p>
        </div>
        <button className="bg-black text-white text-xs px-3 py-1 hover:bg-gray-800 w-fit">
          Read more
        </button>
      </div>
    </div>
  );
}
