"use client";
import { close, loading } from "@/config/swal";
import { getListArticle } from "@/service/article";
import { useEffect, useState } from "react";
import Image from "next/image";

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  createdByName: string;
  thumbnailUrl: string;
  categories: {
    title: string;
  }[];
  files: {
    file_url: string;
    file_alt: string;
  }[];
};

export default function HeroNewsSection() {
  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,
  });

  useEffect(() => {
    initState();
  }, [page, showData, startDateValue, selectedCategories]);

  async function initState() {
    // loading();
    const req = {
      limit: showData,
      page,
      search,
      categorySlug: Array.from(selectedCategories).join(","),
      sort: "desc",
      sortBy: "created_at",
    };

    try {
      const res = await getListArticle(req);
      setArticles(res?.data?.data || []);
      setTotalPage(res?.data?.meta?.totalPage || 1);
    } finally {
      close();
    }
  }

  return (
    <section className="max-w-7xl mx-auto bg-white">
      <div className="flex items-center bg-[#F2F4F3] w-full overflow-hidden mb-4 py-6 px-8">
        <Image
          src="/mikul.png"
          alt="Background"
          width={272}
          height={90}
          className="w-[272px] h-[90px] object-cover border"
          priority
        />
      </div>

      <div className="pb-5">
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-0.5 m-8 ">
          {/* Artikel Utama */}
          {articles.length > 0 && (
            <div className="md:col-span-2 lg:col-span-3 relative">
              <Image
                src={
                  articles[0].thumbnailUrl ||
                  articles[0]?.files?.[0]?.file_url ||
                  "/default-image.jpg"
                }
                alt={articles[0].title}
                width={800}
                height={500}
                className="w-full h-full max-h-[460px] object-cover"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/50 to-transparent p-6 flex flex-col justify-end">
                <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 inline-block mb-2 uppercase w-[130px]">
                  {articles[0].categories?.[0]?.title || "TANPA KATEGORI"}
                </span>
                <h2 className="text-sm md:text-xl lg:text-2xl font-bold text-white leading-snug mb-2 w-full md:w-9/12">
                  {articles[0].title}
                </h2>
                <p className="text-white text-xs">
                  {articles[0].createdByName} -{" "}
                  {new Date(articles[0].createdAt).toLocaleDateString("id-ID", {
                    day: "numeric",
                    month: "long",
                    year: "numeric",
                  })}
                </p>
              </div>
            </div>
          )}

          {/* Artikel Tambahan */}
          <div className="md:col-span-1 lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-2">
            {articles.slice(1, 5).map((article, index) => (
              <div key={index} className="relative">
                <Image
                  src={
                    article.thumbnailUrl ||
                    article?.files?.[0]?.file_url ||
                    "/default-image.jpg"
                  }
                  alt={article.title}
                  width={400}
                  height={240}
                  className="w-full h-56 object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/40 to-transparent p-4 flex flex-col justify-end">
                  <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 inline-block uppercase w-[130px]">
                    {article.categoryName || "TANPA KATEGORI"}
                  </span>
                  <h3 className="text-sm font-semibold text-white leading-snug mb-1">
                    {article.title}
                  </h3>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Iklan / Gambar Bawah */}
        <div className="relative mt-10 mb-2 h-[188px] overflow-hidden flex items-center mx-8 border my-8">
          <Image
            src="/image-kolom.png"
            alt="Berita Utama"
            fill
            className="object-contain"
          />
        </div>
      </div>
    </section>
  );
}
