"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { getListArticle } from "@/service/article";
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;
  }[];
};

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

export default function OnTheSpot() {
  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() {
    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 (error) {
      console.error("Failed to fetch articles:", error);
    }
  }

  return (
    <section className="bg-gradient-to-b from-[#E9EBF3] to-white px-6 py-10">
      <div className="mx-auto max-w-7xl">
        {/* Judul section */}
        <div className="flex items-center gap-3 mb-6">
          <h2 className="text-xl font-bold text-gray-900 uppercase">
            ON THE SPOT
          </h2>
          <span className="w-10 h-[3px] bg-yellow-500 inline-block"></span>
        </div>

        {/* Grid berita */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {articles.map((item) => (
            <Link
              key={item.id}
              href={`/detail/${item.id}`}
              className="flex gap-4 rounded-sm overflow-hidden transition"
            >
              <Image
                src={item.thumbnailUrl || "/placeholder.png"}
                alt={item.title}
                width={140}
                height={100}
                className="w-36 h-28 object-cover rounded-md"
              />
              <div className="flex flex-col justify-center">
                <span className="text-xs font-semibold text-gray-700 flex flex-col items-start">
                  {item.categoryName || item.categories?.[0]?.title}
                  <span className="mt-1 w-5 h-[2px] bg-yellow-500 inline-block"></span>
                </span>
                <h3 className="mt-1 font-bold text-base leading-snug">
                  {item.title}
                </h3>
                <p className="text-sm text-gray-700 mt-1 flex items-center">
                  {item.createdByName || item?.customCreatorName}
                  <span className="ml-2 w-2 h-[2px] bg-yellow-500 inline-block mr-3"></span>
                  {new Date(item.createdAt).toLocaleDateString("en-US", {
                    month: "long",
                    day: "numeric",
                    year: "numeric",
                  })}
                </p>
              </div>
            </Link>
          ))}
        </div>
        <div className="relative my-5 max-w-full h-[450px] 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-[450px] flex justify-center">
                <Image
                  src={bannerAd.contentFileUrl}
                  alt={bannerAd.title || "Iklan Banner"}
                  width={1200} // ukuran dasar untuk responsive
                  height={450}
                  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>
  );
}
