"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Card } from "../ui/card";
import Link from "next/link";
import { useRouter, useParams } from "next/navigation";
import { listData, listArticles } from "@/service/landing/landing";
import { toggleBookmark, getBookmarkSummaryForUser } from "@/service/content";
import { getCookiesDecrypt } from "@/lib/utils";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import { Navigation } from "swiper/modules";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { ThumbsUp, ThumbsDown } from "lucide-react";
import { useTranslations } from "next-intl";

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"
  );
}

export default function MediaUpdate() {
  const t = useTranslations("MediaUpdate");
  const [tab, setTab] = useState<"latest" | "popular">("latest");
  const [contentType, setContentType] = useState<
    "audiovisual" | "audio" | "foto" | "text" | "all"
  >("foto");
  const [dataToRender, setDataToRender] = useState<any[]>([]);
  const [filteredData, setFilteredData] = useState<any[]>([]);
  const [bookmarkedIds, setBookmarkedIds] = useState<Set<number>>(new Set());
  const [loading, setLoading] = useState(true);
  const [currentTypeId, setCurrentTypeId] = useState<string>("1");
  const router = useRouter();
  const params = useParams();
  const MySwal = withReactContent(Swal);

  const slug = params?.slug as string;

  const DEFAULT_IMAGE = "/assets/logo1.png";

  useEffect(() => {
    fetchData(tab);
  }, [tab, slug]);

  useEffect(() => {
    // if (contentType !== "all") {
    //   fetchData(tab);
    // } else {
    //   filterDataByContentType();
    // }
    fetchData(tab);
  }, [contentType]);

  useEffect(() => {
    filterDataByContentType();
  }, [dataToRender]);

  // Function to get typeId based on content type
  function getTypeIdByContentType(contentType: string): string {
    switch (contentType) {
      case "audiovisual":
        return "2";
      case "foto":
        return "1";
      case "audio":
        return "4";
      case "text":
        return "3";
      default:
        return "1";
    }
  }

  // Function to get link based on typeId (same as header.tsx)
  function getLink(item: any) {
    switch (item?.typeId) {
      case 1:
        return `/content/image/detail/${item?.id}`;
      case 2:
        return `/content/video/detail/${item?.id}`;
      case 3:
        return `/content/text/detail/${item?.id}`;
      case 4:
        return `/content/audio/detail/${item?.id}`;
      default:
        return "#";
    }
  }

  // Function to get content type link for "Lihat lebih banyak" button
  function getContentTypeLink() {
    const pathname =
      typeof window !== "undefined" ? window.location.pathname : "";

    const isTenantRoute = pathname.includes("/tenant/");
    const basePath = isTenantRoute ? `/tenant/${slug}/content` : "/content";

    switch (contentType) {
      case "audio":
        return `${basePath}/audio`;
      case "foto":
        return `${basePath}/image`;
      case "audiovisual":
        return `${basePath}/video`;
      case "text":
        return `${basePath}/text`;
      default:
        return `${basePath}/image`;
    }
  }

  // function getContentTypeLink() {
  //   switch (contentType) {
  //     case "audio":
  //       return "/tenant/" + slug + "/content/audio";
  //     case "foto":
  //       return "/tenant/" + slug + "/content/image";
  //     case "audiovisual":
  //       return "/tenant/" + slug + "/content/video";
  //     case "text":
  //       return "/tenant/" + slug + "/content/text";
  //     default:
  //       return "/tenant/" + slug + "/content/image";
  //   }
  // }

  // if (contentType === "all") {
  //   setFilteredData(dataToRender);
  //   return;
  // }

  // Function to filter data by content type

  // function filterDataByContentType() {
  //   const filtered = dataToRender.filter((item) => {
  //     // Determine content type based on item properties
  //     const hasVideo = item.videoUrl || item.videoPath;
  //     const hasAudio = item.audioUrl || item.audioPath;
  //     const hasImage =
  //       item.smallThumbnailLink || item.thumbnailUrl || item.imageUrl;
  //     const hasText = item.content || item.description;

  //     switch (contentType) {
  //       case "audiovisual":
  //         return hasVideo;
  //       case "audio":
  //         return hasAudio && !hasVideo;
  //       case "foto":
  //         return hasImage && !hasVideo && !hasAudio;
  //       case "text":
  //         return hasText && !hasVideo && !hasAudio && !hasImage;
  //       default:
  //         return true;
  //     }
  //   });

  //   setFilteredData(filtered);
  // }

  function filterDataByContentType() {
    const filtered = dataToRender.filter((item) => {
      switch (contentType) {
        case "audiovisual":
          return item.typeId === 2;
        case "audio":
          return item.typeId === 4;
        case "foto":
          return item.typeId === 1;
        case "text":
          return item.typeId === 3;
        default:
          return true;
      }
    });

    setFilteredData(filtered);
  }

  async function fetchData(section: "latest" | "popular") {
    try {
      setLoading(true);

      const typeId = parseInt(getTypeIdByContentType(contentType));
      setCurrentTypeId(typeId.toString());

      // const response = await listArticles(
      //   1,
      //   10,
      //   typeId,
      //   undefined,
      //   undefined,
      //   section === "latest" ? "createdAt" : "viewCount",
      //   slug
      // );

      const response = await listArticles(
        1,
        10,
        typeId,
        undefined,
        undefined,
        section === "latest" ? "createdAt" : "viewCount",
        slug || undefined, // ⬅️ jangan kirim undefined string
      );

      let hasil: any[] = [];

      if (response?.error) {
        // console.error("Articles API failed, fallback ke old API");
        const fallbackRes = await listData(
          typeId.toString(),
          "",
          "",
          20,
          0,
          "",
          "",
          "",
        );
        hasil = fallbackRes?.data?.data?.content || [];
      } else {
        hasil = response?.data?.data || [];
      }

      const transformedData = hasil.map((article: any) => ({
        id: article.id,
        title: article.title,
        category:
          article.categoryName ||
          (article.categories && article.categories[0]?.title) ||
          "Tanpa Kategori",
        createdAt: article.createdAt,
        smallThumbnailLink: article.thumbnailUrl,
        label: article.categoryName,
        clientName: article.clientName,
        typeId: article.typeId,
        ...article,
      }));

      setDataToRender(transformedData);

      const roleId = Number(getCookiesDecrypt("urie"));
      if (roleId && !isNaN(roleId)) {
        const simpananLocal = localStorage.getItem("bookmarkedIds");
        let localSet = new Set<number>();
        if (simpananLocal) {
          localSet = new Set(JSON.parse(simpananLocal));
          setBookmarkedIds(localSet);
        }

        const res = await getBookmarkSummaryForUser();
        const bookmarks =
          res?.data?.data?.recentBookmarks ||
          res?.data?.data?.bookmarks ||
          res?.data?.data ||
          [];
        const ids = new Set<number>(
          (Array.isArray(bookmarks) ? bookmarks : [])
            .map((b: any) => Number(b.articleId ?? b.id ?? b.article?.id))
            .filter((x) => !isNaN(x)),
        );

        const gabungan = new Set([...localSet, ...ids]);
        setBookmarkedIds(gabungan);
        localStorage.setItem(
          "bookmarkedIds",
          JSON.stringify(Array.from(gabungan)),
        );
      }
    } catch (err) {
      console.error("Gagal memuat data:", err);
    } finally {
      setLoading(false);
    }
  }

  const handleSave = async (id: number) => {
    const roleId = Number(getCookiesDecrypt("urie"));
    if (!roleId || isNaN(roleId)) {
      MySwal.fire({
        icon: "warning",
        title: "Login diperlukan",
        text: "Silakan login terlebih dahulu untuk menyimpan artikel.",
        confirmButtonText: "Login Sekarang",
        confirmButtonColor: "#d33",
      });
      return;
    }

    try {
      const res = await toggleBookmark(id);
      if (res?.error) {
        MySwal.fire({
          icon: "error",
          title: "Gagal",
          text: "Tidak dapat menyimpan artikel.",
          confirmButtonColor: "#d33",
        });
      } else {
        const updated = new Set(bookmarkedIds);
        updated.add(Number(id));
        setBookmarkedIds(updated);
        localStorage.setItem(
          "bookmarkedIds",
          JSON.stringify(Array.from(updated)),
        );

        MySwal.fire({
          icon: "success",
          title: "Berhasil",
          text: "Artikel berhasil disimpan ke bookmark.",
          timer: 1500,
          showConfirmButton: false,
        });
      }
    } catch (err) {
      console.error("Error menyimpan bookmark:", err);
      MySwal.fire({
        icon: "error",
        title: "Kesalahan",
        text: "Terjadi kesalahan saat menyimpan artikel.",
      });
    }
  };

  function SafeImage({ src, alt }: { src?: string; alt?: string }) {
    const [imgSrc, setImgSrc] = useState(src || DEFAULT_IMAGE);

    useEffect(() => {
      setImgSrc(src || DEFAULT_IMAGE);
    }, [src]);

    return (
      <Image
        src={imgSrc}
        alt={alt || "Image"}
        fill
        className="object-cover cursor-pointer hover:opacity-90 transition-opacity"
        onError={() => setImgSrc(DEFAULT_IMAGE)}
      />
    );
  }

  return (
    <section className="bg-white px-4 py-10 border max-w-[1350px] mx-auto rounded-md border-[#CDD5DF] my-10">
      <div className="max-w-screen-xl mx-auto">
        <h2 className="text-2xl font-semibold text-center mb-6">
          {t("title")}
        </h2>

        {/* Main Tab */}
        <div className="flex justify-center mb-6 bg-white">
          <Card className="bg-[#FFFFFF] rounded-xl flex flex-row p-3 gap-2 shadow-md border border-gray-200">
            <button
              onClick={() => setTab("latest")}
              className={`px-6 py-3 rounded-lg text-sm font-semibold transition-all duration-200 ${
                tab === "latest"
                  ? "bg-[#C6A455] text-white shadow-sm"
                  : "text-[#C6A455] hover:bg-[#C6A455]/10"
              }`}
            >
              {t("latest")}
            </button>
            <button
              onClick={() => setTab("popular")}
              className={`px-6 py-3 rounded-lg text-sm font-semibold transition-all duration-200 ${
                tab === "popular"
                  ? "bg-[#C6A455] text-white shadow-sm"
                  : "text-[#C6A455] hover:bg-[#C6A455]/10"
              }`}
            >
              {t("popular")}{" "}
            </button>
          </Card>
        </div>

        {/* Content Type Filter */}
        <div className="flex justify-center mb-8">
          <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-4 border-2 border-blue-100 shadow-lg">
            <div className="flex flex-wrap justify-center gap-2">
              {/* <button
                onClick={() => setContentType("all")}
                className={`px-4 py-2 rounded-full text-xs font-semibold transition-all duration-300 transform hover:scale-105 ${
                  contentType === "all" 
                    ? "bg-gradient-to-r from-blue-500 to-indigo-600 text-white shadow-lg ring-2 ring-blue-300" 
                    : "bg-white text-blue-600 border-2 border-blue-200 hover:border-blue-400 hover:shadow-md"
                }`}
              >
                📋 Semua
              </button> */}

              <button
                onClick={() => setContentType("foto")}
                className={`px-4 py-2 rounded-full text-xs font-semibold transition-all duration-300 transform hover:scale-105 ${
                  contentType === "foto"
                    ? "bg-gradient-to-r from-orange-500 to-red-600 text-white shadow-lg ring-2 ring-orange-300"
                    : "bg-white text-orange-600 border-2 border-orange-200 hover:border-orange-400 hover:shadow-md"
                }`}
              >
                📸 {t("image")}
              </button>
              <button
                onClick={() => setContentType("audiovisual")}
                className={`px-4 py-2 rounded-full text-xs font-semibold transition-all duration-300 transform hover:scale-105 ${
                  contentType === "audiovisual"
                    ? "bg-gradient-to-r from-purple-500 to-pink-600 text-white shadow-lg ring-2 ring-purple-300"
                    : "bg-white text-purple-600 border-2 border-purple-200 hover:border-purple-400 hover:shadow-md"
                }`}
              >
                🎬 {t("video")}
              </button>
              <button
                onClick={() => setContentType("audio")}
                className={`px-4 py-2 rounded-full text-xs font-semibold transition-all duration-300 transform hover:scale-105 ${
                  contentType === "audio"
                    ? "bg-gradient-to-r from-green-500 to-emerald-600 text-white shadow-lg ring-2 ring-green-300"
                    : "bg-white text-green-600 border-2 border-green-200 hover:border-green-400 hover:shadow-md"
                }`}
              >
                🎵 Audio
              </button>
              <button
                onClick={() => setContentType("text")}
                className={`px-4 py-2 rounded-full text-xs font-semibold transition-all duration-300 transform hover:scale-105 ${
                  contentType === "text"
                    ? "bg-gradient-to-r from-gray-500 to-slate-600 text-white shadow-lg ring-2 ring-gray-300"
                    : "bg-white text-gray-600 border-2 border-gray-200 hover:border-gray-400 hover:shadow-md"
                }`}
              >
                📝 {t("text")}
              </button>
            </div>
          </div>
        </div>

        {/* Slider */}
        {loading ? (
          <p className="text-center">{t("loadContent")}</p>
        ) : (
          <Swiper
            modules={[Navigation]}
            navigation
            spaceBetween={20}
            slidesPerView={1}
            breakpoints={{
              640: { slidesPerView: 2 },
              1024: { slidesPerView: 4 },
            }}
          >
            {filteredData.map((item) => (
              <SwiperSlide key={item.id}>
                <div className="rounded-xl shadow-md overflow-hidden bg-white">
                  {/* ✅ Kondisi: jika typeId = 3 (text) atau 4 (audio) tampilkan ikon, lainnya tampilkan thumbnail */}
                  {item.typeId === 3 ? (
                    // 📝 TEXT
                    <div className="bg-[#e0c350] flex items-center justify-center h-[204px] text-white">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="90"
                        height="90"
                        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>
                  ) : item.typeId === 4 ? (
                    // 🎵 AUDIO
                    <div className="flex items-center justify-center bg-[#bb3523] w-full h-[204px] text-white">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="100"
                        height="100"
                        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>
                  ) : (
                    // 🎬 FOTO / VIDEO (default)
                    <div className="w-full h-[204px] relative">
                      <Link href={getLink(item)}>
                        <SafeImage
                          src={item.smallThumbnailLink}
                          alt={item.title}
                        />

                        {/* <Image
                          src={item.smallThumbnailLink || "/placeholder.png"}
                          alt={item.title || "No Title"}
                          fill
                          className="object-cover cursor-pointer hover:opacity-90 transition-opacity"
                        /> */}
                      </Link>
                    </div>
                  )}

                  {/* Caption / info */}
                  <div className="p-3">
                    <div className="flex items-center gap-2 text-xs font-semibold flex-row justify-between mb-2">
                      <span className="text-xs text-white px-2 py-0.5 rounded bg-emerald-600">
                        {item.clientName}
                      </span>
                      <span className="text-orange-600">
                        {item.categories
                          ?.map((cat: any) => cat.title)
                          .join(", ")}
                      </span>
                    </div>
                    <p className="text-xs text-gray-500 mb-1">
                      {formatTanggal(item.createdAt)}
                    </p>
                    <Link href={getLink(item)}>
                      <p className="text-sm font-semibold mb-3 line-clamp-2 cursor-pointer hover:text-blue-600 transition-colors">
                        {item.title}
                      </p>
                    </Link>

                    <div className="flex items-center justify-between">
                      <div className="flex gap-2 text-gray-600">
                        <ThumbsUp className="w-4 h-4 cursor-pointer" />
                        <ThumbsDown className="w-4 h-4 cursor-pointer" />
                      </div>
                      <Button
                        onClick={() => handleSave(item.id)}
                        disabled={bookmarkedIds.has(Number(item.id))}
                        variant="default"
                        size="sm"
                        className={`rounded px-4 ${
                          bookmarkedIds.has(Number(item.id))
                            ? "bg-gray-400 cursor-not-allowed text-white"
                            : "bg-red-700 text-white hover:bg-red-500"
                        }`}
                      >
                        {bookmarkedIds.has(Number(item.id))
                          ? t("saved")
                          : t("save")}
                      </Button>
                    </div>
                  </div>
                </div>
              </SwiperSlide>
            ))}
          </Swiper>
        )}

        {/* Lihat lebih banyak - hanya muncul jika ada data */}
        {filteredData.length > 0 && (
          <div className="text-center mt-10">
            <Link href={getContentTypeLink()}>
              <Button
                size={"lg"}
                className="text-[#b3882e] bg-transparent border border-[#b3882e] px-6 py-2 rounded-s-sm text-sm font-medium hover:bg-[#b3882e]/10 transition"
              >
                {t("seeMore")}
              </Button>
            </Link>
          </div>
        )}
      </div>
    </section>
  );
}
