"use client";

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

type Article = {
  id: number;
  title: string;
  createdAt: string;
  createdByName: string;
  slug: string;
  customCreatorName: string;
  thumbnailUrl: string;
  categories: { title: string }[];
};

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

export default function Story() {
  const [articles, setArticles] = useState<Article[]>([]);
  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(() => {
    fetchArticles();
  }, []);

  async function fetchArticles() {
    try {
      const req = {
        limit: "4",
        page: 1,
        search: "",
        categorySlug: "",
        sort: "desc",
        isPublish: true,
        sortBy: "created_at",
      };
      const res = await getListArticle(req);
      setArticles(res?.data?.data || []);
    } catch (error) {
      console.error("Gagal memuat story:", error);
    }
  }

  if (articles.length < 4) return null;

  return (
    <div className="px-4 mb-8">
      <div className="max-w-7xl mx-auto">
        {/* Title */}
        <div className="mb-4">
          <h2 className="text-lg font-bold">Featured Story</h2>
          <div className="h-[2px] w-24 bg-black mt-1"></div>
        </div>

        {/* Grid Story */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {articles.map((item) => (
            <div key={item.id} className="relative overflow-hidden h-72">
              <Link className="flex" href={`/details/${item?.slug}`}>
                <Image
                  src={item.thumbnailUrl || "/dummy.jpg"}
                  alt={item.title}
                  fill
                  className="object-cover"
                />
                <div className="absolute inset-0 bg-black/40"></div>
                <div className="absolute inset-0 flex flex-col items-center justify-center text-center px-4 text-white">
                  <span className="bg-black/70 text-xs px-3 py-1 rounded mb-2">
                    {item.categories[0]?.title || "Uncategorized"}
                  </span>
                  <h3 className="text-sm font-semibold leading-snug line-clamp-3">
                    {item.title}
                  </h3>
                </div>
              </Link>
            </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-contain 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>
    </div>
  );
}
