"use client";

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

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;

  createdByName: string;
  slug: string;
  customCreatorName: string;
  thumbnailUrl: string;
  categories: {
    title: string;
  }[];
  files: {
    fileUrl: string;
    file_alt: string;
  }[];
};

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

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

  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 || [];

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

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

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

  async function initState() {
    // loading();
    const req = {
      limit: showData,
      page,
      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();
    }
  }

  return (
    <section className="max-w-7xl mx-auto bg-white">
      <div className="pb-5">
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-2 m-8 ">
          {articles.length > 0 && (
            <div className="md:col-span-2 lg:col-span-3 relative">
              <Link href={`/details/${articles[0]?.slug}`}>
                <Image
                  src={
                    articles[0]?.files?.[0]?.fileUrl ||
                    articles[0]?.files?.[0]?.fileUrl ||
                    "/default-image.jpg"
                  }
                  alt={articles[0].title}
                  width={800}
                  height={500}
                  className="w-full h-full max-h-[460px] object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/50 to-transparent p-6 flex flex-col justify-end">
                  <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 inline-block mb-2 uppercase w-[130px]">
                    {articles[0].categories?.[0]?.title || "TANPA KATEGORI"}
                  </span>
                  <h2 className="text-sm md:text-xl lg:text-2xl font-bold text-white leading-snug mb-2 w-full md:w-9/12">
                    {articles[0].title}
                  </h2>
                  <p className="text-white text-xs flex items-center gap-2">
                    {articles[0]?.customCreatorName ||
                      articles[0]?.createdByName}{" "}
                    -{" "}
                    <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="md:col-span-1 lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-2">
            {articles.slice(1, 5).map((article, index) => (
              <div key={index} className="relative">
                <Link href={`/details/${article?.slug}`}>
                  <Image
                    src={
                      article.thumbnailUrl ||
                      article?.files?.[0]?.fileUrl ||
                      "/default-image.jpg"
                    }
                    alt={article.title}
                    width={400}
                    height={240}
                    className="w-full h-56 object-cover"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/40 to-transparent p-4 flex flex-col justify-end">
                    <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 inline-block uppercase w-[130px]">
                      {article?.categories?.[0]?.title || "TANPA KATEGORI"}
                    </span>
                    <h3 className="text-sm font-semibold text-white leading-snug mb-1">
                      {article.title}
                    </h3>
                  </div>
                </Link>
              </div>
            ))}
          </div>
        </div>

        <div className="relative mt-10 mb-2 flex justify-center mx-8 border my-8 h-[350px] overflow-hidden bg-white">
          {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="/image-kolom.png"
              alt="Berita Utama"
              width={1200}
              height={188}
              className="object-contain w-full h-[188px]"
            />
          )}
        </div>
      </div>
    </section>
  );
}
