"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;
  slug: string;
  createdByName: string;
  customCreatorName: string;
  thumbnailUrl: string;
  categories: {
    title: string;
  }[];
  files: {
    fileUrl: 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 HeaderNusantara() {
  const [page, setPage] = useState(1);
  const [totalPage, setTotalPage] = useState(1);
  const [articles, setArticles] = useState<Article[]>([]);
  const [showData, setShowData] = useState("100");
  const [search, setSearch] = useState("");
  const [selectedCategories, setSelectedCategories] = useState<any>("");
  const [startDateValue, setStartDateValue] = useState({
    startDate: null,
    endDate: null,
  });

  const pathname = usePathname();
  const pathSegments = pathname.split("/").filter(Boolean);

  const categorySlug = pathSegments[1];
  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",
      isPublish: true,
      sortBy: "created_at",
    };

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

  const healthArticles = articles.filter((article) =>
    article.categories?.some((category) =>
      category.title?.toLowerCase().includes("berita warga")
    )
  );

  const mainArticle = healthArticles[0];
  const otherArticles = healthArticles.slice(1, 3);

  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">
        <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 ">Nusantara</p>
      </div>

      <div className="pb-5">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-2 m-8">
          {mainArticle && (
            <div className="md:col-span-2 relative">
              <Link href={`/details/${mainArticle.slug}`}>
                <Image
                  src={mainArticle.files?.[0]?.fileUrl || "/default-image.jpg"}
                  alt={mainArticle.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]">
                    {mainArticle.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">
                    {mainArticle.title}
                  </h2>
                  <p className="text-white text-xs">
                    {mainArticle?.customCreatorName ||
                      mainArticle.createdByName}{" "}
                    -{" "}
                    {new Date(mainArticle.createdAt).toLocaleDateString(
                      "id-ID",
                      {
                        day: "numeric",
                        month: "long",
                        year: "numeric",
                      }
                    )}
                  </p>
                </div>
              </Link>
            </div>
          )}

          <div className="grid grid-rows-2 gap-2">
            {otherArticles.map((article, index) => (
              <div key={index} className="relative">
                <Link href={`/details/${article.slug}`}>
                  <Image
                    src={
                      article.thumbnailUrl ||
                      article.files?.[0]?.fileUrl ||
                      "/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.categories?.[0]?.title || "TANPA KATEGORI"}
                    </span>
                    <h3 className="text-sm font-semibold text-white leading-snug mb-1">
                      {article.title}
                    </h3>
                  </div>
                </Link>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
