"use client";

import { getListArticle } from "@/service/article";
import { useEffect, useState } from "react";
import Image from "next/image";
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: {
    file_url: string;
    file_alt: string;
  }[];
};

const slugToLabel = (slug: string) => {
  const mapping: Record<string, string> = {
    development: "Pembangunan",
    health: "Kesehatan",
    "citizen-news": "Berita Warga",
  };
  return mapping[slug] || slug.charAt(0).toUpperCase() + slug.slice(1);
};

export default function HeaderCitizen() {
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("5");
  const [search, setSearch] = useState("");
  const [selectedCategories, setSelectedCategories] = useState<any>("");
  const [startDateValue, setStartDateValue] = useState({
    startDate: null,
    endDate: null,
  });

  const pathname = usePathname(); // e.g., "/category/development"
  const pathSegments = pathname.split("/").filter(Boolean); // ["category", "development"]

  const categorySlug = pathSegments[1]; // "development"
  const categoryLabel = slugToLabel(categorySlug);

  useEffect(() => {
    initState();
  }, [page, showData, startDateValue, selectedCategories]);

  async function initState() {
    // loading();
    const req = {
      limit: showData,
      page,
      search,
      categorySlug: Array.from(selectedCategories).join(","),
      sort: "desc",
      sortBy: "created_at",
    };

    try {
      const res = await getListArticle(req);
      setArticles(res?.data?.data || []);
      setTotalPage(res?.data?.meta?.totalPage || 1);
    } finally {
      // close();
    }
  }

  return (
    <section className="max-w-7xl mx-auto bg-white">
      <div className="flex flex-col items-start bg-[#F2F4F3] w-full overflow-hidden  py-6 px-8 gap-3">
        <Image
          src="/mikul.png"
          alt="Background"
          width={272}
          height={90}
          className="w-full md:w-[272px] h-[90px] object-cover border"
          priority
        />
        <p className="text-gray-400 text-sm">
          <Link href="/" className="hover:underline">
            Home
          </Link>{" "}
          {">"} <span className="text-black">{categoryLabel}</span>
        </p>
        <p className="text-3xl font-bold ">Berita Warga</p>
      </div>

      <div className="pb-5">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-2 m-8">
          {/* Gambar besar di kiri */}
          {articles.length > 0 && (
            <div className="md:col-span-2 relative">
              <Link href={`/detail/${articles[0]?.id}`}>
                <Image
                  src={
                    articles[0]?.files?.[0]?.file_url ||
                    articles[0]?.files?.[0]?.file_url ||
                    "/default-image.jpg"
                  }
                  alt={articles[0].title}
                  width={800}
                  height={500}
                  className="w-full h-full max-h-[460px] object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/50 to-transparent p-6 flex flex-col justify-end">
                  <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 inline-block mb-2 uppercase w-[130px]">
                    {articles[0].categories?.[0]?.title || "TANPA KATEGORI"}
                  </span>
                  <h2 className="text-sm md:text-xl lg:text-2xl font-bold text-white leading-snug mb-2 w-full md:w-9/12">
                    {articles[0].title}
                  </h2>
                  <p className="text-white text-xs">
                    {articles[0].createdByName} -{" "}
                    {new Date(articles[0].createdAt).toLocaleDateString(
                      "id-ID",
                      {
                        day: "numeric",
                        month: "long",
                        year: "numeric",
                      }
                    )}
                  </p>
                </div>
              </Link>
            </div>
          )}

          {/* Dua gambar kecil di kanan */}
          <div className="grid grid-rows-2 gap-2">
            {articles.slice(1, 3).map((article, index) => (
              <div key={index} className="relative">
                <Link href={`/detail/${article?.id}`}>
                  <Image
                    src={
                      article.thumbnailUrl ||
                      article?.files?.[0]?.file_url ||
                      "/default-image.jpg"
                    }
                    alt={article.title}
                    width={400}
                    height={240}
                    className="w-full h-56 object-cover"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/40 to-transparent p-4 flex flex-col justify-end">
                    <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 inline-block uppercase w-[130px]">
                      {article.categoryName || "TANPA KATEGORI"}
                    </span>
                    <h3 className="text-sm font-semibold text-white leading-snug mb-1">
                      {article.title}
                    </h3>
                  </div>
                </Link>
              </div>
            ))}
          </div>
        </div>

        <div className="relative mt-10 mb-2 h-[188px] overflow-hidden flex items-center mx-8 border my-8">
          <Image
            src="/image-kolom.png"
            alt="Berita Utama"
            fill
            className="object-contain"
          />
        </div>
      </div>
    </section>
  );
}
