"use client";

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

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;
  }[];
};

export default function Beranda() {
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("4");
  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 (err) {
      console.error("Error fetching articles:", err);
    }
  }

  return (
    <section className="px-6 py-8">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
        {articles.map((item) => (
          <div key={item.id}>
            <Link
              className="relative overflow-hidden group cursor-pointer"
              href={`/details/${item?.slug}`}
            >
              <Image
                src={item.thumbnailUrl || "/placeholder.jpg"}
                alt={item.title}
                width={500}
                height={430}
                className="object-cover w-full h-[430px] group-hover:scale-105 transition-transform duration-500"
              />

              {/* Overlay */}
              <div className="absolute inset-0 bg-black/50 flex flex-col justify-end p-4">
                {/* Category */}
                <span className="absolute top-3 left-3 bg-red-500 text-white text-xs px-2 py-1 rounded">
                  {item.categories?.[0]?.title || "TAK BERKATEGORI"}
                </span>

                {/* Title */}
                <h2 className="text-white font-bold text-lg leading-snug mb-2">
                  {item.title}
                </h2>

                {/* Date */}
                <div className="flex items-center text-white text-xs gap-2">
                  <CalendarDays size={14} />
                  <span>
                    {new Date(item.createdAt).toLocaleDateString("id-ID", {
                      day: "2-digit",
                      month: "long",
                      year: "numeric",
                    })}
                  </span>
                </div>
              </div>
            </Link>
          </div>
        ))}
      </div>
    </section>
  );
}
