"use client";

import { useEffect, useState } from "react";
import PublicationKlFilter from "./publication-filter";
import { Button } from "@/components/ui/button";
import { getCookiesDecrypt } from "@/lib/utils";
import { getBookmarksByUserId, getBookmarksForUser } from "@/service/landing/landing";

const itemsPerPage = 9;

type PublicationCardGridProps = {
  selectedCategory: string;
  title?: string;
  refresh?: boolean;
  categoryFilter?: string[];
  formatFilter?: string[];
  isInstitute?: boolean;
  instituteId?: string;
  sortBy?: string;
};

export default function ForYouCardGrid({
  selectedCategory,
  title,
  refresh,
  isInstitute = false,
  instituteId = "",
}: PublicationCardGridProps) {
  const [currentPage, setCurrentPage] = useState(1);
  const [contentImage, setContentImage] = useState<any[]>([]);
  const [totalPages, setTotalPages] = useState(1);
  const [categoryFilter] = useState<string[]>([]);
  const [formatFilter] = useState<string[]>([]);
  const [sortBy] = useState<string>("createdAt");

  useEffect(() => {
    getDataBookmark();
  }, [currentPage, selectedCategory, title, refresh]);

  async function getDataBookmark() {
    console.log("📡 Fetching bookmark list...");

    try {
      const response = await getBookmarksForUser(1, 12, "desc", "createdAt");
      console.log("✅ Bookmark response:", response);

      const bookmarks =
        response?.data?.data?.content || response?.data?.data || [];
      const totalPage = response?.data?.data?.totalPages || 1;

      setContentImage(bookmarks);
      setTotalPages(totalPage);
    } catch (error) {
      console.error("❌ Gagal memuat bookmark:", error);
      setContentImage([]);
    }
  }

  const goToPage = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <div className="space-y-6">
      {/* Grid Card */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
        {contentImage.length === 0 ? (
          <div className="col-span-3 text-center text-muted-foreground">
            Tidak ada artikel tersimpan.
          </div>
        ) : (
          contentImage.map((item: any, idx: number) => {
            const article = item.article || item; // jaga-jaga kalau API return nested
            return (
              <PublicationKlFilter
                key={idx}
                id={article.id || item.articleId}
                image={
                  article.thumbnailUrl ||
                  article.mediaUpload?.smallThumbnailLink ||
                  "/contributor.png"
                }
                label={article.typeName || article.mediaType?.name || "Artikel"}
                category={
                  article.categories?.map((c: any) => c.title).join(", ") ||
                  article.tags ||
                  "-"
                }
                date={new Date(article.createdAt).toLocaleString("id-ID", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
                  hour: "2-digit",
                  minute: "2-digit",
                  timeZoneName: "short",
                })}
                title={article.title}
                description={article.description || ""}
              />
            );
          })
        )}
      </div>

      {/* Pagination */}
      <div className="flex justify-center gap-2">
        {Array.from({ length: totalPages }, (_, i) => (
          <Button
            key={i}
            variant={currentPage === i + 1 ? "default" : "outline"}
            size="sm"
            onClick={() => goToPage(i + 1)}
          >
            {i + 1}
          </Button>
        ))}
      </div>
    </div>
  );
}

// "use client";

// import { useEffect, useState } from "react";
// import PublicationKlFilter from "./publication-filter";
// import { Button } from "@/components/ui/button";
// import { mediaWishlist } from "@/service/landing/landing";

// const itemsPerPage = 9;

// type PublicationCardGridProps = {
//   selectedCategory: string;
//   title?: string;
//   refresh?: boolean;
//   categoryFilter?: string[];
//   formatFilter?: string[];
//   isInstitute?: boolean;
//   instituteId?: string;
//   sortBy?: string;
// };

// export default function ForYouCardGrid({
//   selectedCategory,
//   title,
//   refresh,

//   isInstitute = false,
//   instituteId = "",
// }: PublicationCardGridProps) {
//   const [currentPage, setCurrentPage] = useState(0);
//   const [contentImage, setContentImage] = useState([]);
//   const [totalPages, setTotalPages] = useState(1);
//   const [categoryFilter] = useState([]);
//   const [formatFilter] = useState([]);
//   const [sortBy] = useState();

//   useEffect(() => {
//     getDataImage();
//   }, [currentPage, selectedCategory, title, refresh]);

//   async function getDataImage() {
//     const filter =
//       categoryFilter?.length > 0
//         ? categoryFilter?.sort().join(",")
//         : selectedCategory || "";

//     const name = title ?? "";
//     const format = formatFilter?.join(",") ?? "";

//     const response = await mediaWishlist(
//       "1",
//       isInstitute ? instituteId : "",
//       name,
//       filter,
//       "12",
//       currentPage,
//       sortBy,
//       format
//     );

//     setTotalPages(response?.data?.data?.totalPages || 1);
//     setContentImage(response?.data?.data?.content || []);
//   }

//   const goToPage = (page: number) => {
//     setCurrentPage(page);
//   };

//   return (
//     <div className="space-y-6">
//       {/* Grid Card */}
//       <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
//         {contentImage.length === 0 ? (
//           <div className="col-span-3 text-center text-muted-foreground">
//             Tidak ada konten ditemukan.
//           </div>
//         ) : (
//           contentImage.map((item: any, idx: number) => (
//             <PublicationKlFilter
//               key={item.id}
//               id={item.id} // ✅ tambahkan ini
//               image={item.mediaUpload?.smallThumbnailLink}
//               label={item.mediaType?.name ?? "UNKNOWN"}
//               category={item.tags ?? "-"}
//               date={new Date(item?.mediaUpload?.createdAt).toLocaleString(
//                 "id-ID",
//                 {
//                   day: "2-digit",
//                   month: "short",
//                   year: "numeric",
//                   hour: "2-digit",
//                   minute: "2-digit",
//                   timeZoneName: "short",
//                 }
//               )}
//               title={item?.mediaUpload?.title}
//               description={""} // Optional: Tambahkan jika tersedia dari API
//             />
//           ))
//         )}
//       </div>

//       {/* Pagination */}
//       <div className="flex justify-center gap-2">
//         {Array.from({ length: totalPages }, (_, i) => (
//           <Button
//             key={i}
//             variant={currentPage === i + 1 ? "default" : "outline"}
//             size="sm"
//             onClick={() => goToPage(i + 1)}
//           >
//             {i + 1}
//           </Button>
//         ))}
//       </div>
//     </div>
//   );
// }
