"use client";

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

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  slug: string;
  thumbnailUrl?: string;
};

export default function ImageCard() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [page] = useState(1);
  const [showData] = useState("6");
  const [search] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);

  async function initState() {
    const req = {
      limit: showData,
      page,
      search,
      categorySlug: "",
      sort: "desc",
      isPublish: true,
      title: search,
      categoryId: selectedCategory,
      sortBy: "created_at",
    };

    try {
      const res = await getListArticle(req);
      setArticles(res?.data?.data || []);
    } catch (err) {
      console.error("Error get article:", err);
    }
  }

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

  return (
    <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
      {articles.map((item) => (
        <Link key={item.id} href={`/details/${item.slug}?type=image`}>
          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-md transition duration-300 overflow-hidden">
            {/* IMAGE */}
            <div className="relative h-[200px] w-full">
              <Image
                src={item.thumbnailUrl || "/image/novita2.png"}
                alt={item.title}
                fill
                className="object-cover"
              />
            </div>

            {/* CONTENT */}
            <div className="p-5 space-y-3">
              {/* BADGE + TAG */}
              <div className="flex items-center gap-2 text-xs">
                <span className="bg-red-600 text-white px-2 py-[3px] rounded-md font-medium">
                  POLRI
                </span>
                <span className="text-gray-500 uppercase tracking-wide">
                  {item.categoryName}
                </span>
              </div>

              {/* DATE */}
              <p className="text-xs text-gray-400">
                {new Date(item.createdAt).toLocaleDateString("id-ID", {
                  day: "2-digit",
                  month: "long",
                  year: "numeric",
                })}
              </p>

              {/* TITLE */}
              <h3 className="font-semibold text-[15px] leading-snug line-clamp-2 hover:text-[#966314] transition">
                {item.title}
              </h3>

              {/* EXCERPT */}
              <p className="text-sm text-gray-500 line-clamp-2 leading-relaxed">
                {item.description}
              </p>
            </div>
          </div>
        </Link>
      ))}
    </div>
  );
}
