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

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

export default function LatestNews() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("5");
  const pathname = usePathname();
  const currentSlug = pathname.split("/")[2] || "";

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

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

  const mainArticle = articles[0];
  const secondArticle = articles[1];

  return (
    <div className="max-w-7xl mx-auto px-4 py-10 grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2">
        <h1 className="text-3xl font-bold mb-2">
          {" "}
          {currentSlug ? ` ${currentSlug}` : "Berita Terkini"}
        </h1>
        <p className="text-gray-600 mb-6">
          Kolom ini berisi berita-berita yang saat ini sedang menjadi sorotan
          atau terkait dengan peristiwa terbaru.
        </p>

        {articles.slice(0, 5).map((article, index) => (
          <Link
            key={article.id}
            href={`/detail/${article.id}`}
            className={`grid grid-cols-1 md:grid-cols-2 gap-4 mb-6 items-center`}
          >
            {/* Gambar */}
            <div className={`relative ${index === 0 ? "h-64" : "h-64"} w-full`}>
              <Image
                src={article.thumbnailUrl}
                alt={article.title}
                fill
                className="object-cover rounded"
              />
            </div>

            {/* Konten */}
            <div className="flex flex-col justify-center">
              <span className="bg-yellow-500 text-white px-2 py-1 text-xs font-semibold w-fit mb-2">
                BERITA TERKINI
              </span>
              <h2 className="text-xl font-bold hover:text-red-500 mb-2">
                {article.title}
              </h2>
              <p className="text-xs text-gray-500 mb-2">
                by {article.createdByName} • {formatDate(article.createdAt)} •
                💬 0
              </p>
              <p className="text-sm text-gray-700 mb-3 line-clamp-3">
                {article.description}
              </p>
              <button className="bg-black text-white text-xs px-4 py-2 w-fit hover:bg-gray-800">
                READ MORE
              </button>
            </div>
          </Link>
        ))}
      </div>

      {/* KANAN: Advertisement */}
      <div className="w-full">
        <div className="border p-4 bg-white flex flex-col items-center">
          <p className="text-center text-sm text-gray-600 mb-2">
            Smart & Responsive
          </p>
          <h3 className="text-center text-md font-bold mb-4">ADVERTISEMENT</h3>
          <div className="relative w-full h-[300px] bg-gray-100">
            <Image
              src="/adversment.png"
              alt="Advertisement"
              fill
              className="object-contain"
            />
          </div>
          <button className="mt-4 text-xs bg-black text-white px-4 py-2 hover:bg-gray-800">
            LEARN MORE
          </button>
        </div>
      </div>
    </div>
  );
}

function formatDate(dateStr: string): string {
  const options: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "long",
    day: "numeric",
  };
  return new Date(dateStr).toLocaleDateString("id-ID", options);
}
