// components/landing-page/breaking-news.tsx
"use client";

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

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  slug: 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 BreakingNews() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [editorArticles, setEditorArticles] = useState<Article[]>([]);
  const [newsArticles, setNewsArticles] = useState<Article[]>([]);
  const [activeTab, setActiveTab] = useState<
    "trending" | "comments" | "latest"
  >("trending");
  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: "8",
        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 breaking news:", error);
    }
  }

  useEffect(() => {
    fetchEditorArticles();
  }, []);

  async function fetchEditorArticles() {
    try {
      const req = {
        limit: "6", // jumlah artikel yg ditampilkan
        page: 1,
        search: "",
        categorySlug: "",
        sort: "desc",
        isPublish: true,
        sortBy: "created_at",
      };

      const res = await getListArticle(req);
      setEditorArticles(res?.data?.data || []);
      setNewsArticles(res?.data?.data || []);
    } catch (error) {
      console.error("Gagal memuat Editor's Pick:", error);
    }
  }

  const mainArticle = articles[0];
  const sideArticles = articles.slice(1, 5);
  const popularArticles = articles.slice(1, 5);

  return (
    <section className="max-w-7xl mx-auto px-4 py-8">
      <div className="flex flex-row gap-4">
        <div className="w-9/12">
          {mainArticle && (
            <div className="">
              <Link href={`/details/${mainArticle?.slug}`}>
                <div className="grid md:grid-cols-2 gap-6 items-center">
                  {/* LEFT - Image */}
                  <div className="relative w-full h-[220px] md:h-[300px] overflow-hidden">
                    <Image
                      src={
                        mainArticle.thumbnailUrl ||
                        mainArticle.files?.[0]?.fileUrl ||
                        "/placeholder.png"
                      }
                      alt={mainArticle.title}
                      fill
                      className="object-cover"
                    />
                  </div>

                  {/* RIGHT - Content */}
                  <div className="flex flex-col justify-center">
                    <span className="bg-yellow-400 text-black px-2 py-1 text-xs font-bold inline-block mb-3 w-fit">
                      {mainArticle.categoryName?.toUpperCase()}
                    </span>

                    <h2 className="text-xl md:text-2xl font-bold mb-2 leading-snug hover:underline cursor-pointer">
                      {mainArticle.title}
                    </h2>

                    <div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
                      <span className="font-semibold text-blue-600">
                        {mainArticle.createdByName}
                      </span>
                      <div className="flex items-center gap-1">
                        <Calendar size={14} />
                        {new Date(mainArticle.createdAt).toLocaleDateString(
                          "en-GB",
                          {
                            day: "2-digit",
                            month: "long",
                            year: "numeric",
                          }
                        )}
                      </div>
                      <span>0</span>
                    </div>

                    <p className="text-sm text-gray-600 mb-4 line-clamp-3">
                      {mainArticle.description}
                    </p>

                    <button className="border border-gray-400 px-4 py-2 text-xs font-semibold hover:bg-black hover:text-white transition w-fit">
                      READ MORE
                    </button>
                  </div>
                </div>
              </Link>
            </div>
          )}
          <div className="relative mb-2 h-[120px] overflow-hidden flex items-center border my-8">
            {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 className="mt-10">
            <h2 className="text-lg md:text-xl font-bold mb-4 border-b pb-2">
              Editor's Pick
            </h2>

            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {editorArticles?.map((article) => {
                const imageUrl =
                  article.thumbnailUrl ||
                  article.files?.[0]?.fileUrl ||
                  "/placeholder.png";

                const category =
                  article.categoryName ||
                  article.categories?.[0]?.title ||
                  "NEWS";

                return (
                  <div key={article.id} className="group">
                    <Link href={`/details/${article?.slug}`}>
                      {/* Image */}
                      <div className="relative w-full h-[180px] overflow-hidden mb-3">
                        <Image
                          src={imageUrl}
                          alt={article.title}
                          fill
                          className="object-cover group-hover:scale-105 transition-transform duration-300"
                        />
                        <span className="absolute bottom-2 left-2 bg-yellow-400 text-black px-2 py-1 text-[10px] font-bold">
                          {category.toUpperCase()}
                        </span>
                      </div>

                      {/* Title */}
                      <h3 className="font-semibold text-sm md:text-base mb-2 leading-snug group-hover:underline cursor-pointer">
                        {article.title}
                      </h3>

                      {/* Date */}
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <Calendar size={14} />
                        {new Date(article.createdAt).toLocaleDateString(
                          "en-GB",
                          {
                            day: "2-digit",
                            month: "long",
                            year: "numeric",
                          }
                        )}
                      </div>
                    </Link>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="relative mb-2 h-[120px] overflow-hidden flex items-center border my-8">
            {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>
          {/* News Index Section */}
          <div className="mt-10">
            <h2 className="text-lg md:text-xl font-bold mb-4 border-b pb-2">
              News Index
            </h2>

            <div className="flex flex-col gap-8">
              {newsArticles?.map((article) => {
                const imageUrl =
                  article.thumbnailUrl ||
                  article.files?.[0]?.fileUrl ||
                  "/placeholder.png";

                return (
                  <div key={article.id}>
                    <Link
                      className="grid grid-cols-1 md:grid-cols-3 gap-4"
                      href={`/details/${article?.slug}`}
                    >
                      {/* LEFT - Image */}
                      <div className="relative w-full h-[180px] md:h-[140px] rounded-md overflow-hidden md:col-span-1">
                        <Image
                          src={imageUrl}
                          alt={article.title}
                          fill
                          className="object-cover"
                        />
                      </div>

                      {/* RIGHT - Content */}
                      <div className="md:col-span-2 flex flex-col justify-center">
                        <h3 className="font-bold text-lg md:text-xl mb-2 leading-snug hover:underline cursor-pointer">
                          {article.title}
                        </h3>

                        <div className="flex items-center gap-4 text-xs text-gray-500 mb-2">
                          <span className="font-semibold text-blue-600">
                            {article.createdByName || "DODDODYDOD"}
                          </span>
                          <div className="flex items-center gap-1">
                            <Calendar size={14} />
                            {new Date(article.createdAt).toLocaleDateString(
                              "en-GB",
                              {
                                day: "2-digit",
                                month: "long",
                                year: "numeric",
                              }
                            )}
                          </div>
                          <span>0</span>
                        </div>

                        <p className="text-sm text-gray-600 line-clamp-2">
                          {article.description}
                        </p>
                      </div>
                    </Link>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* RIGHT - Tabs + Side Articles */}
        <div className="w-3/12">
          {/* Tabs */}
          <div className="flex gap-4 border-b mb-4 text-sm font-semibold">
            {["trending", "comments", "latest"].map((tab) => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab as any)}
                className={`pb-2 ${
                  activeTab === tab
                    ? "border-b-2 border-black text-black"
                    : "text-gray-500"
                }`}
              >
                {tab.charAt(0).toUpperCase() + tab.slice(1)}
              </button>
            ))}
          </div>

          {/* List */}
          <div className="space-y-4">
            {sideArticles.map((a) => (
              <div key={a.id} className="flex gap-3 items-center">
                <Link
                  className="flex gap-3 items-center"
                  href={`/details/${a?.slug}`}
                >
                  <div className="relative w-20 h-16 flex-shrink-0 rounded overflow-hidden">
                    <Image
                      src={
                        a.thumbnailUrl ||
                        a.files?.[0]?.fileUrl ||
                        "/placeholder.png"
                      }
                      alt={a.title}
                      fill
                      className="object-cover"
                    />
                  </div>
                  <div className="flex-1">
                    <h4 className="text-sm font-semibold line-clamp-2 hover:underline">
                      {a.title}
                    </h4>
                    <div className="flex items-center gap-1 text-xs text-gray-500 mt-1">
                      <Calendar size={12} />
                      {new Date(a.createdAt).toLocaleDateString("en-GB", {
                        day: "2-digit",
                        month: "long",
                        year: "numeric",
                      })}
                    </div>
                  </div>
                </Link>
              </div>
            ))}
          </div>
          <div className="relative w-[1111px] max-w-full h-[300px] overflow-hidden flex items-center mx-auto border my-6 rounded">
            {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>

          {/* Follow Us Section */}
          <div className="mt-10">
            <h2 className="text-lg md:text-xl font-bold mb-4 border-b pb-2">
              Follow Us
            </h2>

            <div className="grid grid-cols-2 gap-4">
              <div className="flex flex-col items-center justify-center border rounded p-4">
                <span className="text-3xl text-blue-600 font-bold">Bē</span>
                <span className="text-lg font-semibold mt-2">140</span>
                <span className="text-xs text-gray-500">Followers</span>
              </div>

              <div className="flex flex-col items-center justify-center border rounded p-4">
                <span className="text-3xl text-pink-500 font-bold">◉</span>
                <span className="text-lg font-semibold mt-2">643</span>
                <span className="text-xs text-gray-500">Followers</span>
              </div>
            </div>
          </div>

          {/* Popular News Section */}
          <div className="mt-10">
            <h2 className="text-lg md:text-xl font-bold mb-4 border-b pb-2">
              Popular News
            </h2>

            {/* Artikel Utama (Top 1) */}
            {popularArticles.length > 0 && (
              <div className="mb-6">
                <Link href={`/details/${popularArticles[0]?.slug}`}>
                  <div className="relative w-full h-[220px] md:h-[280px] rounded overflow-hidden">
                    <Image
                      src={
                        popularArticles[0].thumbnailUrl ||
                        popularArticles[0].files?.[0]?.fileUrl ||
                        "/placeholder.png"
                      }
                      alt={popularArticles[0].title}
                      fill
                      className="object-cover"
                    />
                  </div>
                  <div className="flex items-start justify-between mt-3">
                    <h3 className="font-bold text-base md:text-lg leading-snug max-w-[85%]">
                      {popularArticles[0].title}
                    </h3>
                    <span className="text-3xl font-bold text-gray-300">01</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
                    <span>154 Shares</span>
                  </div>
                </Link>
              </div>
            )}

            {/* Artikel 2 - 5 */}
            <div className="space-y-4">
              {popularArticles.slice(1, 5).map((a, i) => (
                <div key={a.id}>
                  <Link
                    className="flex items-center gap-3"
                    href={`/details/${a?.slug}`}
                  >
                    {/* Nomor Urut */}
                    <div className="w-10 h-10 flex items-center justify-center rounded-full border text-sm font-bold text-gray-500">
                      {String(i + 2).padStart(2, "0")}
                    </div>

                    {/* Judul & Info */}
                    <div className="flex-1">
                      <h4 className="text-sm font-semibold line-clamp-2 hover:underline">
                        {a.title}
                      </h4>
                      <div className="flex items-center gap-2 text-xs text-gray-400 mt-1">
                        <span>{154 - i} Shares</span>
                      </div>
                    </div>
                  </Link>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Banner Slot */}
      <div className="mt-8 text-center py-10 text-gray-400 font-bold tracking-widest">
        {bannerAd ? (
          <a
            href={bannerAd.redirectLink}
            target="_blank"
            rel="noopener noreferrer"
            className="block w-full"
          >
            <div className="relative w-full h-auto 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>
  );
}
