"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Archive, Star } from "lucide-react";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { getBookmarks } from "@/service/content";
import { BookmarkItem } from "@/service/content";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import { Navigation } from "swiper/modules";

// Format tanggal
function formatTanggal(dateString: string) {
  if (!dateString) return "";
  return (
    new Date(dateString)
      .toLocaleString("id-ID", {
        day: "2-digit",
        month: "short",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
        hour12: false,
        timeZone: "Asia/Jakarta",
      })
      .replace(/\./g, ":") + " WIB"
  );
}

function getLink(item: BookmarkItem) {
  switch (item.article?.typeId) {
    case 1:
      return `/content/image/detail/${item.article?.id}`;
    case 2:
      return `/content/video/detail/${item.article?.id}`;
    case 3:
      return `/content/text/detail/${item.article?.id}`;
    case 4:
      return `/content/audio/detail/${item.article?.id}`;
    default:
      return "#";
  }
}

type ForYouCardGridProps = {
  filterType: "My Collections" | "Archives" | "Favorites";
  selectedCategory?: string;
};

export default function ForYouCardGrid({ filterType }: ForYouCardGridProps) {
  const [bookmarks, setBookmarks] = useState<BookmarkItem[]>([]);
  const [loading, setLoading] = useState(true);
  const MySwal = withReactContent(Swal);

  useEffect(() => {
    fetchBookmarks();
  }, [filterType]);

  const fetchBookmarks = async () => {
    try {
      setLoading(true);
      const response = await getBookmarks(1, 50, filterType);
      if (!response?.error) {
        setBookmarks(response.data?.data || []);
      } else {
        MySwal.fire("Error", "Gagal memuat bookmark.", "error");
      }
    } catch (err) {
      console.error(err);
      MySwal.fire("Error", "Terjadi kesalahan saat memuat bookmark.", "error");
    } finally {
      setLoading(false);
    }
  };

  const grouped = {
    image: bookmarks.filter((b) => b.article?.typeId === 1).slice(0, ),
    video: bookmarks.filter((b) => b.article?.typeId === 2).slice(0, 5),
    text: bookmarks.filter((b) => b.article?.typeId === 3).slice(0, 5),
    audio: bookmarks.filter((b) => b.article?.typeId === 4).slice(0, 5),
  };

  const renderImageVideoCard = (bookmark: BookmarkItem) => (
    <div className="rounded-xl shadow-md bg-white hover:shadow-lg transition-shadow overflow-hidden">
      <div className="relative w-full h-[200px]">
        <Link href={getLink(bookmark)}>
          <Image
            src={bookmark.article?.thumbnailUrl || "/placeholder.png"}
            alt={bookmark.article?.title || "No Title"}
            fill
            className="object-cover"
          />
        </Link>
      </div>
      <div className="p-3">
        <p className="text-xs text-gray-500 mb-1">
          Disimpan: {formatTanggal(bookmark.createdAt)}
        </p>
        <Link href={getLink(bookmark)}>
          <p className="text-sm font-semibold line-clamp-2 cursor-pointer hover:text-blue-600 transition-colors">
            {bookmark.article?.title}
          </p>
        </Link>
        <div className="flex gap-2 mt-3">
          <Button
            size="sm"
            variant="outline"
            className="flex items-center gap-1 text-gray-700 border-gray-300 hover:bg-gray-100"
          >
            <Archive className="w-4 h-4" /> Archive
          </Button>
          <Button
            size="sm"
            variant="outline"
            className="flex items-center gap-1 text-yellow-600 border-yellow-200 hover:bg-yellow-50"
          >
            <Star className="w-4 h-4" /> Favorite
          </Button>
        </div>
      </div>
    </div>
  );

  const renderTextCard = (bookmark: BookmarkItem) => (
    <div className="cursor-pointer rounded-lg shadow-md overflow-hidden bg-white dark:bg-black dark:border dark:border-gray-500 hover:shadow-lg transition-shadow">
      {/* Background kuning & ikon dokumen */}
      <div className="bg-[#e0c350] flex items-center justify-center h-[170px] text-white">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="100"
          height="100"
          viewBox="0 0 16 16"
        >
          <path
            fill="currentColor"
            d="M5 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V5.414a1.5 1.5 0 0 0-.44-1.06L9.647 1.439A1.5 1.5 0 0 0 8.586 1zM4 3a1 1 0 0 1 1-1h3v2.5A1.5 1.5 0 0 0 9.5 6H12v7a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1zm7.793 2H9.5a.5.5 0 0 1-.5-.5V2.207z"
          />
        </svg>
      </div>

      {/* Konten bawah */}
      <div className="p-4 flex flex-col gap-2">
        <p className="text-xs text-gray-500 mb-1">
          Disimpan: {formatTanggal(bookmark.createdAt)}
        </p>
        <Link
          href={getLink(bookmark)}
          className="font-semibold text-gray-900 dark:text-white text-base leading-snug line-clamp-3"
        >
          {bookmark.article?.title}
        </Link>
        <div className="flex gap-2 mt-3">
          <Button
            size="sm"
            variant="outline"
            className="flex items-center gap-1 text-gray-700 border-gray-300 hover:bg-gray-100"
          >
            <Archive className="w-4 h-4" /> Archive
          </Button>
          <Button
            size="sm"
            variant="outline"
            className="flex items-center gap-1 text-yellow-600 border-yellow-200 hover:bg-yellow-50"
          >
            <Star className="w-4 h-4" /> Favorite
          </Button>
        </div>
      </div>
    </div>
  );

  const renderAudioCard = (bookmark: BookmarkItem) => (
    <div className="cursor-pointer bg-white dark:bg-black dark:border dark:border-gray-500 rounded-xl shadow-md hover:shadow-lg transition-shadow overflow-hidden">
      {/* Background merah & ikon audio */}
      <div className="flex items-center justify-center bg-[#bb3523] w-full h-[170px] text-white">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="120"
          height="120"
          viewBox="0 0 20 20"
        >
          <path
            fill="currentColor"
            d="M14.702 2.226A1 1 0 0 1 16 3.18v6.027a5.5 5.5 0 0 0-1-.184V6.18L8 8.368V15.5a2.5 2.5 0 1 1-1-2V5.368a1 1 0 0 1 .702-.955zM8 7.32l7-2.187V3.18L8 5.368zM5.5 14a1.5 1.5 0 1 0 0 3a1.5 1.5 0 0 0 0-3m13.5.5a4.5 4.5 0 1 1-9 0a4.5 4.5 0 0 1 9 0m-2.265-.436l-2.994-1.65a.5.5 0 0 0-.741.438v3.3a.5.5 0 0 0 .741.438l2.994-1.65a.5.5 0 0 0 0-.876"
          />
        </svg>
      </div>

      {/* Caption */}
      <Link href={getLink(bookmark)} className="p-4">
        <p className="text-xs text-gray-500 mb-1">
          Disimpan: {formatTanggal(bookmark.createdAt)}
        </p>
        <p className="text-base font-semibold text-black dark:text-white line-clamp-3">
          {bookmark.article?.title}
        </p>
      </Link>
      <div className="flex gap-2 mx-2">
        <Button
          size="sm"
          variant="outline"
          className="flex items-center gap-1 text-gray-700 border-gray-300 hover:bg-gray-100"
        >
          <Archive className="w-4 h-4" /> Archive
        </Button>
        <Button
          size="sm"
          variant="outline"
          className="flex items-center gap-1 text-yellow-600 border-yellow-200 hover:bg-yellow-50"
        >
          <Star className="w-4 h-4" /> Favorite
        </Button>
      </div>
    </div>
  );

  const renderSection = (
    title: string,
    items: BookmarkItem[],
    type: "imagevideo" | "text" | "audio"
  ) => {
    if (!items.length) return null;

    return (
      <div className="mb-10">
        <h2 className="text-xl font-bold text-gray-800 mb-4">{title}</h2>
        <Swiper
          spaceBetween={20}
          slidesPerView={1.2}
          breakpoints={{
            640: { slidesPerView: 2.2 },
            1024: { slidesPerView: 3.2 },
            1280: { slidesPerView: 4.2 },
          }}
          navigation
          modules={[Navigation]}
        >
          {items.map((bookmark) => (
            <SwiperSlide key={bookmark.id}>
              {type === "imagevideo"
                ? renderImageVideoCard(bookmark)
                : type === "text"
                ? renderTextCard(bookmark)
                : renderAudioCard(bookmark)}
            </SwiperSlide>
          ))}
        </Swiper>
      </div>
    );
  };

  if (loading)
    return (
      <div className="text-center py-12 text-gray-500">Memuat konten...</div>
    );

  if (bookmarks.length === 0)
    return (
      <div className="text-center py-12">
        <div className="text-gray-400 text-6xl mb-4">📂</div>
        <h3 className="text-xl font-semibold text-gray-600 mb-2">
          Tidak Ada Konten di {filterType}
        </h3>
      </div>
    );

  return (
    <div className="space-y-10">
      {renderSection("📸 Image", grouped.image, "imagevideo")}
      {renderSection("🎬 Video", grouped.video, "imagevideo")}
      {renderSection("📝 Text", grouped.text, "text")}
      {renderSection("🎵 Audio", grouped.audio, "audio")}
    </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>
//   );
// }
