"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;
  slug: string;
  createdByName: string;
  customCreatorName?: string;
  thumbnailUrl?: string;
  categories?: { title: string }[];
};

export default function NewsTerkini() {
  const [articles, setArticles] = useState<Article[]>([]);
  const [popular, setPopular] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);

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

  async function loadData() {
    setLoading(true);

    try {
      const res = await getListArticle({
        limit: "20",
        page: 1,
        search: "",
        isPublish: true,
        sort: "desc",
        sortBy: "created_at",
      });

      const data = res?.data?.data || [];
      setArticles(data.slice(0, 5));
      setPopular(data.slice(0, 5)); // 5 teratas sebagai "TERBANYAK DIBAGIKAN"
    } catch (err) {
      console.log(err);
    }

    setLoading(false);
  }

  const formatDate = (d: string) =>
    new Date(d).toLocaleDateString("id-ID", {
      day: "numeric",
      month: "long",
      year: "numeric",
    });

  if (loading)
    return (
      <p className="text-center py-10 text-gray-500">
        Memuat berita terbaru...
      </p>
    );

  return (
    <section className="max-w-7xl mx-auto px-4 grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-6">
      <div>
        <h2 className="text-lg font-bold text-gray-900">BERITA TERKINI</h2>
        <div className="w-14 h-1 bg-green-600 mt-1 mb-4"></div>

        <div className="space-y-6">
          {articles.map((item) => (
            <Link
              key={item.id}
              href={`/details/${item.slug}`}
              className="block border-b pb-6"
            >
              <div className="flex gap-4">
                <div className="flex-1">
                  {/* CATEGORY */}
                  <p className="text-[11px] text-green-700 font-semibold mb-1">
                    {item.categoryName || "Kategori"}
                  </p>

                  {/* JUDUL */}
                  <h3 className="font-bold text-base leading-snug line-clamp-2">
                    {item.title}
                  </h3>

                  {/* DESKRIPSI */}
                  <p className="text-sm text-gray-600 line-clamp-2 mt-1">
                    {item.description}
                  </p>

                  {/* AUTHOR + DATE */}
                  <p className="text-xs text-gray-400 mt-2">
                    By {item.customCreatorName || item.createdByName} —{" "}
                    {formatDate(item.createdAt)}
                  </p>
                </div>
                <div className="relative w-40 h-28 rounded overflow-hidden flex-shrink-0">
                  <Image
                    src={item.thumbnailUrl || "/placeholder.jpg"}
                    alt={item.title}
                    fill
                    className="object-cover"
                  />
                </div>
              </div>
            </Link>
          ))}
        </div>

        {/* LOAD MORE */}
        <div className="text-center mt-4 text-green-600 text-sm cursor-pointer">
          LOAD MORE ↓
        </div>
      </div>

      {/* ========================== */}
      {/*   KOLOM KANAN - POPULER    */}
      {/* ========================== */}

      <div className="lg:col-span-1">
        <h2 className="text-lg font-bold text-gray-900">TERBANYAK DIBAGIKAN</h2>
        <div className="w-14 h-1 bg-green-600 mt-1 mb-4"></div>

        <div className="space-y-4">
          {popular.map((item, index) => (
            <Link
              key={item.id}
              href={`/details/${item.slug}`}
              className="flex gap-3 border-b pb-4"
            >
              {/* NOMOR */}
              <div className="text-green-600 font-extrabold text-3xl leading-none">
                {(index + 1).toString().padStart(2, "0")}
              </div>

              <div className="flex-1">
                <p className="text-[10px] text-gray-500">
                  {item.categories?.[0]?.title || "Kategori"}
                </p>
                <h4 className="font-semibold text-sm leading-snug line-clamp-2">
                  {item.title}
                </h4>
                <p className="text-[10px] text-gray-400 mt-1">
                  {formatDate(item.createdAt)}
                </p>
              </div>

              {/* THUMBNAIL KECIL */}
              <div className="relative w-16 h-14 rounded overflow-hidden">
                <Image
                  src={item.thumbnailUrl || "/placeholder.jpg"}
                  alt={item.title}
                  fill
                  className="object-cover"
                />
              </div>
            </Link>
          ))}
        </div>

        {/* ========================== */}
        {/*     BANNER KANAN PPS       */}
        {/* ========================== */}

        <div className="mt-6">
          <div className="relative h-[180px] border rounded-lg overflow-hidden mb-6">
            <Image
              src="/image-kolom.png"
              alt="Kolom PPS"
              fill
              className="object-contain bg-white"
            />
          </div>

          <div className="relative h-[180px] border rounded-lg overflow-hidden">
            <Image
              src="/image-kolom.png"
              alt="Kolom PPS"
              fill
              className="object-contain bg-white"
            />
          </div>
        </div>
      </div>
    </section>
  );
}
