"use client";

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

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

export default function OpinionNews() {
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("6");
  const [search] = useState("");
  const [selectedCategories] = useState<any>("");
  const [startDateValue] = useState({
    startDate: null,
    endDate: null,
  });

  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 (err) {
      console.error("Error fetching articles:", err);
    }
  }

  return (
    <section className="max-w-screen-xl mx-auto px-4 py-10">
      <div className="">
        {/* TITLE */}
        <div className="mb-4">
          <h2 className="text-xl font-black text-[#000]">BERITA OPINI</h2>
          <div className="w-10 h-1 bg-green-600 mt-1 rounded"></div>
        </div>

        {/* GRID 4 KOLOM */}
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6">
          {articles.slice(0, 4).map((item) => (
            <Link href={`/details/${item.slug}`} key={item.id}>
              <div>
                {/* GAMBAR */}
                <div className="relative w-full h-56 rounded-lg overflow-hidden">
                  <Image
                    src={item.thumbnailUrl || "/placeholder.jpg"}
                    alt={item.title}
                    fill
                    className="object-cover"
                  />

                  {/* BADGE CATEGORY DI DALAM GAMBAR */}
                  <div className="absolute bottom-2 left-2">
                    <span className="px-3 py-1 text-[10px] font-semibold bg-green-600 text-white rounded">
                      {item.categoryName || "Kategori"}
                    </span>
                  </div>
                </div>

                {/* JUDUL */}
                <h3 className="mt-2 text-base font-bold leading-snug line-clamp-2">
                  {item.title}
                </h3>

                {/* AUTHOR + DATE */}
                <div className="text-[11px] mt-2 flex items-center gap-1 text-gray-700">
                  <span className="font-semibold">
                    By {item.customCreatorName || item.createdByName || "Admin"}
                  </span>
                  <span className="text-yellow-500">-</span>
                  <span>
                    {new Date(item.publishedAt).toLocaleDateString("id-ID", {
                      day: "numeric",
                      month: "long",
                      year: "numeric",
                    })}
                  </span>
                </div>
              </div>
            </Link>
          ))}
        </div>

        <div className="relative h-[160px] w-full overflow-hidden rounded-xl mt-6">
          <Image
            src="/image-kolom.png"
            alt="Kolom PPS"
            fill
            className="object-contain bg-white"
          />
        </div>
      </div>
    </section>
  );
}
