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

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  createdByName: 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 LatestNews() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("5");
  const pathname = usePathname();
  const currentSlug = pathname.split("/")[2] || "";
  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);
    }
  }
  useEffect(() => {
    fetchArticles();
  }, []);

  async function fetchArticles() {
    try {
      const req = {
        limit: showData,
        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 artikel:", error);
    }
  }

  const mainArticle = articles[0];
  const secondArticle = articles[1];

  return (
    <div className="max-w-7xl mx-auto px-4 py-10 grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2">
        <h1 className="text-3xl font-bold mb-2">
          {" "}
          {currentSlug ? ` ${currentSlug}` : "Berita Terkini"}
        </h1>
        <p className="text-gray-600 mb-6">
          Kolom ini berisi berita-berita yang saat ini sedang menjadi sorotan
          atau terkait dengan peristiwa terbaru.
        </p>

        {articles.slice(0, 5).map((article, index) => (
          <Link
            key={article.id}
            href={`/detail/${article.id}`}
            className={`grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 items-center`}
          >
            {/* Gambar */}
            <div className={`relative ${index === 0 ? "h-64" : "h-64"} w-full`}>
              <Image
                src={article.thumbnailUrl}
                alt={article.title}
                fill
                className="object-cover rounded"
              />
            </div>

            {/* Konten */}
            <div className="flex flex-col justify-center">
              <span className="bg-yellow-500 text-white px-2 py-1 text-xs font-semibold w-fit mb-2">
                BERITA TERKINI
              </span>
              <h2 className="text-xl font-bold hover:text-red-500 mb-2">
                {article.title}
              </h2>
              <p className="text-xs text-gray-500 mb-2">
                by {article.createdByName} • {formatDate(article.createdAt)} •
                💬 0
              </p>
              <p className="text-sm text-gray-700 mb-3 line-clamp-3">
                {article.description}
              </p>
              <button className="bg-black text-white text-xs px-4 py-2 w-fit hover:bg-gray-800">
                READ MORE
              </button>
            </div>
          </Link>
        ))}
      </div>

      {/* KANAN: Advertisement */}
      <div className="w-full">
        <div className="border p-4 bg-white flex flex-col items-center">
          <p className="text-center text-sm text-gray-600 mb-2">
            Smart & Responsive
          </p>
          <h3 className="text-center text-md font-bold mb-4">ADVERTISEMENT</h3>
          <div className="relative w-full h-[300px] bg-gray-100">
            {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>
          <button className="mt-4 text-xs bg-black text-white px-4 py-2 hover:bg-gray-800">
            LEARN MORE
          </button>
        </div>
      </div>
    </div>
  );
}

function formatDate(dateStr: string): string {
  const options: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "long",
    day: "numeric",
  };
  return new Date(dateStr).toLocaleDateString("id-ID", options);
}
