"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;
  createdByName: string;
  thumbnailUrl: string;
  categories: {
    title: string;
  }[];
  files: {
    file_url: string;
    file_alt: string;
  }[];
};

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

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

  async function initState() {
    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);
    } catch (error) {
      console.error("Gagal memuat artikel:", error);
    }
  }

  const highlightArticles = articles.slice(0, 2);
  const otherArticles = articles.slice(2);

  return (
    <section className="bg-gradient-to-b from-[#f4f6fa] to-white px-6 py-10">
      <div className="mx-auto max-w-7xl grid grid-cols-1 md:grid-cols-2 gap-6">
        {highlightArticles.map((item) => (
          <Link
            key={item.id}
            href={`/news/${item.id}`}
            className="relative rounded-xl overflow-hidden group"
          >
            <Image
              src={item.thumbnailUrl || "/default-image.jpg"}
              alt={item.title}
              width={600}
              height={400}
              className="w-full h-[400px] object-cover group-hover:scale-105 transition-transform duration-300"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/70 to-transparent" />
            <div className="absolute bottom-4 left-4 text-white">
              <span className="text-xs font-semibold flex flex-col items-start">
                {item.categories?.[0]?.title || "Uncategorized"}
                <span className="w-6 h-[2px] bg-yellow-500 inline-block"></span>
              </span>
              <h2 className="mt-2 text-lg font-bold leading-snug">
                {item.title}
              </h2>
              <p className="text-sm mt-1 flex items-center">
                {item.createdByName}
                <span className="ml-2 w-2 h-[2px] bg-yellow-500 inline-block mr-3"></span>
                {new Date(item.createdAt).toLocaleDateString("en-US", {
                  month: "long",
                  day: "numeric",
                  year: "numeric",
                })}
              </p>
            </div>
          </Link>
        ))}

        {otherArticles.slice(1, 3).map((item) => (
          <Link
            key={item.id}
            href={`/news/${item.id}`}
            className="flex gap-4 rounded-sm overflow-hidden transition"
          >
            <Image
              src={item.thumbnailUrl || "/default-image.jpg"}
              alt={item.title}
              width={180}
              height={120}
              className="w-52 h-44 object-cover"
            />
            <div className="p-3 flex flex-col justify-center">
              <span className="text-xs font-semibold text-gray-700 flex flex-col items-start">
                {item.categories?.[0]?.title || "Uncategorized"}
                <span className="mt-1 w-5 h-[2px] bg-yellow-500 inline-block"></span>
              </span>

              <h3 className="mt-1 font-bold text-base leading-snug">
                {item.title}
              </h3>
              <p className="text-sm text-gray-700 mt-1 flex items-center">
                {item.createdByName}
                <span className="ml-2 w-2 h-[2px] bg-yellow-500 inline-block mr-3"></span>
                {new Date(item.createdAt).toLocaleDateString("en-US", {
                  month: "long",
                  day: "numeric",
                  year: "numeric",
                })}
              </p>
            </div>
          </Link>
        ))}
      </div>
    </section>
  );
}
