"use client";

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

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 OnTheSpot() {
  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() {
    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 (error) {
      console.error("Failed to fetch articles:", error);
    }
  }

  return (
    <section className="bg-gradient-to-b from-[#E9EBF3] to-white px-6 py-10">
      <div className="mx-auto max-w-7xl">
        {/* Judul section */}
        <div className="flex items-center gap-3 mb-6">
          <h2 className="text-xl font-bold text-gray-900 uppercase">
            ON THE SPOT
          </h2>
          <span className="w-10 h-[3px] bg-yellow-500 inline-block"></span>
        </div>

        {/* Grid berita */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {articles.map((item) => (
            <Link
              key={item.id}
              href={`/news/${item.id}`}
              className="flex gap-4 rounded-sm overflow-hidden transition"
            >
              <Image
                src={item.thumbnailUrl || "/placeholder.png"}
                alt={item.title}
                width={140}
                height={100}
                className="w-36 h-28 object-cover rounded-md"
              />
              <div className="flex flex-col justify-center">
                <span className="text-xs font-semibold text-gray-700 flex flex-col items-start">
                  {item.categoryName || item.categories?.[0]?.title}
                  <span className="mt-1 w-5 h-[2px] bg-yellow-500 inline-block"></span>
                </span>
                <h3 className="mt-1 font-bold text-base leading-snug">
                  {item.title}
                </h3>
                <p className="text-sm text-gray-700 mt-1 flex items-center">
                  {item.createdByName}
                  <span className="ml-2 w-2 h-[2px] bg-yellow-500 inline-block mr-3"></span>
                  {new Date(item.createdAt).toLocaleDateString("en-US", {
                    month: "long",
                    day: "numeric",
                    year: "numeric",
                  })}
                </p>
              </div>
            </Link>
          ))}
        </div>
        <div className="relative my-5 max-w-full h-[125px] overflow-hidden flex items-center mx-auto border">
          <Image
            src="/image-kolom.png"
            alt="Berita Utama"
            fill
            className="object-cover"
          />
        </div>
      </div>
    </section>
  );
}
