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

export default function HeaderEkonomi() {
  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);
    }
  }

  if (articles.length === 0) return null;

  const featuredArticle = articles[0];
  const recentPosts = articles.slice(1, 5); // Ambil 4 artikel berikutnya

  return (
    <section className="py-16 px-6 bg-white">
      <div className="max-w-7xl mx-auto">
        <h2 className="text-3xl font-bold text-center">Ekonomi</h2>
        <p className="text-center text-gray-500 mt-2 mb-10">
          Kolom ini berisi berita-berita yang saat ini sedang menjadi sorotan
          atau terkait dengan Ekonomi.
        </p>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-10">
          <div className="md:col-span-2 overflow-y-auto max-h-[1400px] pr-2">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {articles.map((article) => (
                <div key={article.id}>
                  <Link href={`/details/${article.slug}`}>
                    <Image
                      src={article.thumbnailUrl || "/default.jpg"}
                      alt={article.title}
                      width={600}
                      height={400}
                      className="w-full h-[250px] object-cover rounded-md"
                    />
                    <p className="text-xs font-semibold text-red-600 mt-4 uppercase">
                      {article.categories?.[0]?.title ||
                        article.categoryName ||
                        "BERITA"}
                    </p>
                    <h3 className="text-lg font-bold mt-1">{article.title}</h3>
                    <p className="text-sm text-gray-600 mt-2 line-clamp-3">
                      {article.description}
                    </p>
                    <p className="text-sm text-gray-700 mt-4">
                      By <strong>{article.createdByName}</strong> —{" "}
                      {new Date(article.createdAt).toLocaleDateString("en-US", {
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                      })}
                    </p>
                    <Link
                      href={`/details/${article.slug}`}
                      className="mt-2 inline-block text-sm text-red-600 font-semibold hover:underline"
                    >
                      READ MORE &gt;
                    </Link>
                  </Link>
                </div>
              ))}
            </div>

            <div className="flex justify-end mt-10 gap-2">
              {Array.from({ length: totalPage }).map((_, i) => (
                <button
                  key={i}
                  onClick={() => setPage(i + 1)}
                  className={`w-9 h-9 rounded-full border border-gray-300 text-sm ${
                    page === i + 1
                      ? "bg-red-400 text-white font-bold"
                      : "text-gray-700 hover:bg-gray-200"
                  }`}
                >
                  {i + 1}
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-6 sticky top-28 h-fit">
            <h4 className="text-xl font-bold">Recent Posts</h4>
            {recentPosts.map((post, index) => (
              <div key={post.id}>
                <Link className="flex gap-3" href={`/details/${post.slug}`}>
                  <Image
                    src={post.thumbnailUrl || "/default.jpg"}
                    alt={post.title}
                    width={80}
                    height={80}
                    className="w-20 h-20 object-cover rounded-md"
                  />
                  <div className="flex-1">
                    <p className="text-xs font-semibold text-red-600 uppercase">
                      {post.categories?.[0]?.title ||
                        post.categoryName ||
                        "BERITA"}
                    </p>
                    <h5 className="text-sm font-semibold leading-snug">
                      {post.title}
                    </h5>
                    <p className="text-xs text-gray-500 mt-1">
                      {new Date(post.createdAt).toLocaleDateString("en-US", {
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                      })}
                    </p>
                  </div>
                  <div className="text-3xl font-bold text-red-300 leading-none">
                    {String(index + 1).padStart(2, "0")}
                  </div>
                </Link>
              </div>
            ))}
            <div className="relative  max-w-full h-[300px] overflow-hidden flex items-center mx-auto my-6 rounded">
              <Image
                src="/earphone.png"
                alt="Berita Utama"
                fill
                className="object-contain rounded"
              />
            </div>
            <div className="border rounded-md p-4 space-y-4">
              <h4 className="text-lg font-semibold">
                Subscribe us to get the latest news!
              </h4>

              <div>
                <label
                  htmlFor="email"
                  className="block text-xs font-semibold text-gray-600 mb-1"
                >
                  Email address:
                </label>
                <input
                  id="email"
                  type="email"
                  placeholder="Your email address"
                  className="w-full border rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-red-400"
                />
              </div>

              <button className="w-full bg-red-400 hover:bg-red-500 text-white font-semibold py-2 rounded transition">
                SIGN UP
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
