"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { Calendar, Eye, MessageSquare } from "lucide-react";
import { getListArticle } from "@/service/article";
import Link from "next/link";

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  slug: string;
  createdByName: string;
  thumbnailUrl: string;
  categories: { title: string }[];
  files: { fileUrl: string; file_alt: string }[];
};

type PaginationMeta = {
  total: number;
  page: number;
  limit: number;
  last_page: number;
};

export default function BreakingNews() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [limit] = useState("8");
  const [meta, setMeta] = useState<PaginationMeta | null>(null);

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

  async function fetchArticles() {
    try {
      setLoading(true);

      const req = {
        limit,
        page,
        search: "",
        categorySlug: "",
        sort: "desc",
        isPublish: true,
        sortBy: "created_at",
      };

      const res = await getListArticle(req);

      setArticles(res?.data?.data || []);
      setMeta(res?.data?.meta || null); // pastikan API mengembalikan meta
    } catch (error) {
      console.error("Gagal memuat artikel:", error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="max-w-7xl mx-auto px-4 py-10 bg-white">
      {/* Judul */}
      <h2 className="text-center text-2xl font-bold mb-8 border-b pb-2">
        Berita Populer
      </h2>

      {/* Loader */}
      {loading && <p className="text-center">Memuat data...</p>}

      {/* Grid berita */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {articles.map((article) => (
          <div
            key={article.id}
            className="bg-white border overflow-hidden shadow-sm hover:shadow-md transition"
          >
            <Link href={`/details/${article?.slug}`}>
              <div className="relative w-full h-40">
                <Image
                  src={
                    article.thumbnailUrl ||
                    article.files?.[0]?.fileUrl ||
                    "/placeholder.jpg"
                  }
                  alt={article.files?.[0]?.file_alt || article.title}
                  fill
                  className="object-cover"
                />
                <span className="absolute top-2 left-2 bg-black text-white text-xs px-2 py-1 rounded">
                  {article.categoryName || article.categories?.[0]?.title}
                </span>
              </div>
              <div className="p-3">
                <h3 className="font-semibold text-base leading-snug mb-2 line-clamp-2">
                  {article.title}
                </h3>
                <p className="text-sm text-gray-600 line-clamp-2 mb-3">
                  {article.description}
                </p>
                <div className="flex items-center gap-4 text-xs text-gray-500">
                  <span className="flex items-center gap-1">
                    <Calendar className="w-3 h-3" />{" "}
                    {new Date(article.createdAt).toLocaleDateString("id-ID", {
                      day: "numeric",
                      month: "long",
                      year: "numeric",
                    })}
                  </span>
                  <span className="flex items-center gap-1">
                    <Eye className="w-3 h-3" /> {0}
                  </span>
                  <span className="flex items-center gap-1">
                    <MessageSquare className="w-3 h-3" /> {0}
                  </span>
                </div>
              </div>
            </Link>
          </div>
        ))}
      </div>

      {meta && (
        <div className="flex justify-center mt-8">
          <ul className="flex items-center gap-2 flex-wrap">
            {/* Tombol Prev */}
            <li>
              <button
                disabled={page === 1}
                onClick={() => setPage((prev) => Math.max(prev - 1, 1))}
                className={`px-3 py-1 rounded ${
                  page === 1
                    ? "bg-gray-300 text-gray-500 cursor-not-allowed"
                    : "bg-gray-200 hover:bg-gray-300"
                }`}
              >
                Prev
              </button>
            </li>

            {/* Nomor Halaman 1 - last_page */}
            {Array.from({ length: meta.last_page }, (_, i) => i + 1).map(
              (p) => (
                <li key={p}>
                  <button
                    onClick={() => setPage(p)}
                    className={`px-3 py-1 rounded ${
                      page === p
                        ? "bg-blue-600 text-white"
                        : "bg-gray-200 hover:bg-gray-300"
                    }`}
                  >
                    {p}
                  </button>
                </li>
              ),
            )}

            {/* Tombol Next */}
            <li>
              <button
                disabled={page === meta.last_page}
                onClick={() =>
                  setPage((prev) => Math.min(prev + 1, meta.last_page))
                }
                className={`px-3 py-1 rounded ${
                  page === meta.last_page
                    ? "bg-gray-300 text-gray-500 cursor-not-allowed"
                    : "bg-gray-200 hover:bg-gray-300"
                }`}
              >
                Next
              </button>
            </li>
          </ul>
        </div>
      )}
    </section>
  );
}
