"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { getListArticle } from "@/service/article";
import { Calendar } from "lucide-react";
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 BottomArticlesSection() {
  const [articles, setArticles] = useState<Article[]>([]);

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

  async function fetchArticles() {
    try {
      const req = {
        limit: "6",
        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 artikel bawah:", error);
    }
  }

  return (
    <section className="py-10 px-4 md:px-8 bg-[#E9EBF3]">
      <div className="max-w-[1300px] mx-auto grid grid-cols-1 md:grid-cols-3 gap-8">
        {articles.map((item) => (
          <div key={item.id}>
            <Link className="flex gap-4" href={`/details/${item?.slug}`}>
              <div className="relative w-[120px] h-[100px] shrink-0">
                <Image
                  src={
                    item.thumbnailUrl ||
                    item.files?.[0]?.fileUrl ||
                    "/default.jpg"
                  }
                  alt={item.title}
                  fill
                  className="object-cover"
                />
              </div>
              <div className="flex flex-col justify-center gap-2">
                <span className="text-xs text-[#2481D3] font-bold uppercase tracking-wide">
                  {item.categoryName}
                </span>
                <h3 className="text-sm font-semibold font-serif leading-tight text-slate-800 w-10/12">
                  {item.title}
                </h3>
                <div className="flex flex-row item-center gap-3">
                  <div className="text-sm  text-black">
                    {item.createdByName}{" "}
                  </div>
                  <div className="text-blue-400 mt-1">
                    <Calendar size={12} />
                  </div>
                  <div className="text-sm ">
                    {new Date(item.createdAt).toLocaleDateString("en-GB", {
                      day: "2-digit",
                      month: "long",
                      year: "numeric",
                    })}
                  </div>
                </div>
              </div>
            </Link>
          </div>
        ))}
      </div>
    </section>
  );
}
