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

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  publishedAt: string;
  createdByName: string;
  slug: 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;
};

const MoreNews = () => {
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("4");
  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 || [1];

      // 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() {
    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);
    } catch (err) {
      console.error("Error fetching articles:", err);
    }
  }
  return (
    <section className="max-w-7xl mx-auto py-16 bg-white">
      <h2 className="text-xl font-semibold mb-6 border-b pb-2 relative">
        More News{" "}
        <span className="absolute bottom-[-2px] left-0 w-16 h-[2px] bg-teal-400"></span>
      </h2>

      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
        {articles.map((item) => (
          <div key={item?.id} className="space-y-2">
            <Link className="space-y-2" href={`/details/${item?.slug}`}>
              <div className="relative">
                <Image
                  src={item.thumbnailUrl}
                  alt={item.title}
                  width={400}
                  height={250}
                  className="w-full h-48 object-cover rounded-md"
                />
                <span className="absolute bottom-2 left-2 bg-red-500 text-white text-xs font-semibold px-2 py-1 rounded">
                  {item.categories?.[0]?.title}
                </span>
              </div>
              <h3 className="text-sm font-semibold leading-snug hover:text-teal-600 cursor-pointer">
                {item.title}
              </h3>
              <p className="text-gray-500 text-xs flex items-center gap-1">
                <Timer className="text-teal-600" size={15} />
                <span>
                  {new Date(item?.publishedAt).toLocaleDateString("id-ID", {
                    day: "numeric",
                    month: "long",
                    year: "numeric",
                  })}
                </span>
              </p>
            </Link>
          </div>
        ))}
      </div>

      <div className="mt-10 flex items-center justify-center gap-4">
        {/* Garis Kiri */}
        <div className="h-px bg-gray-300 flex-1" />

        {/* Tombol */}
        <button className="px-6 py-2 border border-gray-300 rounded text-sm hover:bg-gray-100 transition">
          LOAD MORE
        </button>

        {/* Garis Kanan */}
        <div className="h-px bg-gray-300 flex-1" />
      </div>
      <div className="max-w-7xl relative my-5  h-[125px] overflow-hidden flex items-center mx-auto border">
        {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>
    </section>
  );
};

export default MoreNews;
