"use client";
import { getListArticle } from "@/service/article";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import Link from "next/link";
import { getAdvertise } from "@/service/advertisement";

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

const slugToLabel = (slug: string) => {
  const mapping: Record<string, string> = {
    development: "Pembangunan",
    health: "Kesehatan",
    "citizen-news": "Berita Warga",
  };
  return mapping[slug] || slug.charAt(0).toUpperCase() + slug.slice(1);
};

type Advertise = {
  id: number;
  title: string;
  description: string;
  placement: string;
  contentFileUrl: string;
  redirectLink: string;
};

export default function HealthNews() {
  const [activeTab, setActiveTab] = useState("comments");
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("100");
  const [search, setSearch] = useState("");
  const [selectedCategories, setSelectedCategories] = useState<any>("");
  const [startDateValue, setStartDateValue] = useState({
    startDate: null,
    endDate: null,
  });

  const pathname = usePathname();
  const pathSegments = pathname.split("/").filter(Boolean);

  const [bannerAd, setBannerAd] = useState<Advertise | null>(null);

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

  async function initStateAdver() {
    const req = {
      limit: 100,
      page: 1,
      sort: "desc",
      sortBy: "created_at",
      isPublish: true,
    };

    try {
      const res = await getAdvertise(req);
      const data: Advertise[] = res?.data?.data || [1];

      // filter iklan dengan placement = "banner"
      const banner = data.find((ad) => ad.placement === "jumbotron");

      if (banner) {
        setBannerAd(banner);
      }
    } catch (err) {
      console.error("Error fetching advertisement:", err);
    }
  }

  const categorySlug = pathSegments[1];
  const categoryLabel = slugToLabel(categorySlug);

  useEffect(() => {
    initState();
  }, [page, showData, startDateValue, selectedCategories, activeTab]);

  async function initState() {
    let sortBy = "created_at";
    if (activeTab === "comments") sortBy = "comment_count";
    if (activeTab === "trending") sortBy = "view_count";

    // loading();
    const req = {
      limit: showData,
      page: 1,
      search,
      categorySlug: Array.from(selectedCategories).join(","),
      sort: "desc",
      isPublish: true,
      sortBy: "created_at",
    };

    try {
      const res = await getListArticle(req);
      setArticles(res?.data?.data || []);
      setTotalPage(res?.data?.meta?.totalPage || 1);
    } finally {
      // close();
    }
  }

  const kesehatanArticles = articles.filter((article) =>
    article.categories?.some((category) =>
      category.title?.toLowerCase().includes("berita warga")
    )
  );
  const itemsPerPage = 2;
  const calculatedTotalPage = Math.ceil(
    kesehatanArticles.length / itemsPerPage
  );

  const paginatedArticles = kesehatanArticles.slice(
    (page - 1) * itemsPerPage,
    page * itemsPerPage
  );

  function truncateText(text: string, wordLimit: number) {
    const words = text.split(" ");
    if (words.length <= wordLimit) return text;
    return words.slice(0, wordLimit).join(" ") + "...";
  }

  return (
    <div className="bg-white grid grid-cols-1 lg:grid-cols-3 gap-6 py-10 px-8">
      <div className="lg:col-span-2 space-y-10">
        {paginatedArticles.map((item) => (
          <div key={item.id}>
            <Link
              className="flex flex-col md:flex-row gap-6"
              href={`/details/${item?.slug}`}
            >
              <div className="relative w-full md:w-1/2 h-64">
                <Image
                  src={item.thumbnailUrl || "/placeholder.png"}
                  alt={item.title}
                  fill
                  className="object-cover rounded"
                />
                <span className="absolute top-3 left-3 bg-yellow-400 text-black px-3 py-1 text-xs font-bold">
                  {item.categories[0]?.title || "Pembangunan"}
                </span>
              </div>

              {/* Content */}
              <div className="flex-1">
                <h2 className="text-xl font-bold text-[#16324F] hover:text-green-600 cursor-pointer">
                  {item.title}
                </h2>
                <div className="text-sm text-gray-600 mt-2">
                  BY{" "}
                  <span className="text-green-600 font-semibold">
                    {item?.customCreatorName || item.createdByName || "Admin"}
                  </span>{" "}
                  • {new Date(item.createdAt).toLocaleDateString("id-ID")}
                </div>
                <p className="mt-3 text-gray-700">
                  {truncateText(item.description, 20)}
                </p>
                <button className="mt-4 px-4 py-2 border border-gray-400 text-gray-700 hover:bg-black hover:text-white transition">
                  READ MORE
                </button>
              </div>
            </Link>
          </div>
        ))}

        {/* Pagination */}
        <div className="flex items-center justify-center gap-2 mt-6">
          <button
            onClick={() => setPage((prev) => Math.max(prev - 1, 1))}
            disabled={page === 1}
            className="px-3 py-1 border"
          >
            &lt;
          </button>

          {Array.from({ length: calculatedTotalPage }, (_, i) => i + 1)
            .filter((p) => {
              return (
                p === 1 ||
                p === calculatedTotalPage ||
                (p >= page - 1 && p <= page + 1)
              );
            })
            .map((p, idx, arr) => {
              const prev = arr[idx - 1];
              const showEllipsis = prev && p - prev > 1;

              return (
                <span key={p} className="flex items-center">
                  {showEllipsis && <span className="px-2">...</span>}
                  <button
                    onClick={() => setPage(p)}
                    className={`px-3 py-1 ${
                      page === p ? "bg-green-600 text-white" : "border"
                    }`}
                  >
                    {p}
                  </button>
                </span>
              );
            })}

          <button
            onClick={() =>
              setPage((prev) => Math.min(prev + 1, calculatedTotalPage))
            }
            disabled={page === calculatedTotalPage}
            className="px-3 py-1 border"
          >
            &gt;
          </button>
        </div>
      </div>

      <div className="space-y-6">
        <div className="w-full h-[400px] relative">
          {bannerAd ? (
            <a
              href={bannerAd.redirectLink}
              target="_blank"
              rel="noopener noreferrer"
              className="block w-full"
            >
              <div className="relative w-full h-[350px] flex justify-center">
                <Image
                  src={bannerAd.contentFileUrl}
                  alt={bannerAd.title || "Iklan Banner"}
                  width={1200} // ukuran dasar untuk responsive
                  height={350}
                  className="object-cover w-full h-full"
                />
              </div>
            </a>
          ) : (
            <Image
              src="/kolom.png"
              alt="Berita Utama"
              width={1200}
              height={188}
              className="object-contain w-full h-[188px]"
            />
          )}
        </div>

        <div>
          <h3 className="text-lg font-semibold mb-2">Connect with us</h3>
          <div className="h-1 w-20 bg-green-600 mb-4"></div>
          <div className="grid grid-cols-3 gap-2">
            <div className="bg-blue-500 text-white text-center p-3">
              <p className="text-xl font-bold">138</p>
              <p className="text-sm">Followers</p>
            </div>
            <div className="bg-red-600 text-white text-center p-3">
              <p className="text-xl font-bold">205k</p>
              <p className="text-sm">Subscribers</p>
            </div>
            <div className="bg-yellow-400 text-black text-center p-3">
              <p className="text-xl font-bold">23.9k</p>
              <p className="text-sm">Followers</p>
            </div>
          </div>
        </div>

        <div>
          <div className="flex gap-4 border-b">
            {["trending", "comments", "latest"].map((tab) => (
              <button
                key={tab}
                className={`pb-2 capitalize ${
                  activeTab === tab
                    ? "border-b-2 border-green-600 text-green-600"
                    : "text-gray-600"
                }`}
                onClick={() => {
                  setPage(1);
                  setActiveTab(tab);
                }}
              >
                {tab}
              </button>
            ))}
          </div>

          <div className="mt-4 space-y-4">
            {articles.slice(0, 5).map((item) => (
              <div key={item.id} className="flex gap-3 items-center">
                <Link
                  className="flex gap-3 items-center"
                  href={`/details/${item?.slug}`}
                >
                  <Image
                    src={item.thumbnailUrl || "/no-image.jpg"}
                    alt={item.title}
                    width={80}
                    height={60}
                    className="object-cover rounded"
                  />
                  <div>
                    <h3 className="font-semibold text-sm">{item.title}</h3>
                    <p className="text-xs text-gray-500">
                      {new Date(item.createdAt).toLocaleDateString()}
                    </p>
                  </div>
                </Link>
              </div>
            ))}
          </div>
          <div className="">
            <h2 className="text-sm border-b-2 border-gray-300 font-bold mb-4">
              Recommended
            </h2>
            <div className=" w-full">
              <div className="relative w-full aspect-video mb-5">
                <Link href={`/details/${articles[0]?.slug}`}>
                  <Image
                    src={
                      articles[0]?.thumbnailUrl ||
                      articles[0]?.files?.[0]?.fileUrl ||
                      "/default-image.jpg"
                    }
                    alt={"articles[0]?.title"}
                    fill
                    sizes="(max-width: 1024px) 100vw, 33vw"
                    className="object-cover"
                  />
                  <div className="absolute inset-0 bg-black/30" />
                  <div className="absolute bottom-0.5 left-2 text-white">
                    <h3 className=" font-semibold text-base mb-1">
                      {articles[0]?.title}
                    </h3>
                    <p className=" text-xs  mb-2 flex items-center gap-2">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                      >
                        <g fill="none">
                          <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                          <path
                            fill="currentColor"
                            d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2m0 2a8 8 0 1 0 0 16a8 8 0 0 0 0-16m0 2a1 1 0 0 1 .993.883L13 7v4.586l2.707 2.707a1 1 0 0 1-1.32 1.497l-.094-.083l-3-3a1 1 0 0 1-.284-.576L11 12V7a1 1 0 0 1 1-1"
                          />
                        </g>
                      </svg>{" "}
                      {new Date(articles[0]?.createdAt).toLocaleDateString(
                        "id-ID",
                        {
                          day: "numeric",
                          month: "long",
                          year: "numeric",
                        }
                      )}
                    </p>
                  </div>
                </Link>
              </div>

              <div className="space-y-5">
                {articles?.slice(1, 4).map((article, index) => (
                  <div key={index}>
                    <Link
                      className="flex gap-3"
                      href={`/details/${article?.slug}`}
                    >
                      <div className="relative w-[120px] h-[86px] shrink-0">
                        <Image
                          src={
                            article?.thumbnailUrl ||
                            article?.files?.[0]?.fileUrl ||
                            "/default-image.jpg"
                          }
                          alt={"article?.title"}
                          fill
                          className="object-cover"
                        />
                      </div>
                      <div>
                        <h4 className="text-sm font-semibold mb-3">
                          {article?.title}
                        </h4>
                        <p className="text-xs text-gray-500 flex gap-2 items-center">
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="16"
                            height="16"
                            viewBox="0 0 24 24"
                          >
                            <g fill="none">
                              <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                              <path
                                fill="currentColor"
                                d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2m0 2a8 8 0 1 0 0 16a8 8 0 0 0 0-16m0 2a1 1 0 0 1 .993.883L13 7v4.586l2.707 2.707a1 1 0 0 1-1.32 1.497l-.094-.083l-3-3a1 1 0 0 1-.284-.576L11 12V7a1 1 0 0 1 1-1"
                              />
                            </g>
                          </svg>{" "}
                          {new Date(articles[0]?.createdAt).toLocaleDateString(
                            "id-ID",
                            {
                              day: "numeric",
                              month: "long",
                              year: "numeric",
                            }
                          )}
                        </p>
                      </div>
                    </Link>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
