"use client";
import { Clock, MessageCircle } from "lucide-react";
import { Card } from "../ui/card";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { getListArticle } from "@/service/article";
import Link from "next/link";
import { getAdvertise } from "@/service/advertisement";

type Article = {
  id: number;
  title: string;
  description: string;
  categoryName: string;
  createdAt: string;
  slug: string;
  createdByName: string;
  thumbnailUrl: string;
  categories: {
    title: string;
  }[];
  files: {
    fileUrl: string;
    file_alt: string;
  }[];
};

type Advertise = {
  id: number;
  title: string;
  description: string;
  placement: string;
  contentFileUrl: string;
  redirectLink: string;
};

export default function Beranda() {
  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 [bannerAd, setBannerAd] = useState<Advertise | null>(null);
  const [bannerImageAd, setBannerImageAd] = useState<Advertise | null>(null);
  useEffect(() => {
    initStateAdver();
  }, []);

  async function initStateAdver() {
    const req = {
      limit: 100,
      page: 1,
      sort: "desc",
      sortBy: "created_at",
      isPublish: true,
    };

    try {
      const res = await getAdvertise(req);
      const data: Advertise[] = res?.data?.data || [];

      // ambil iklan placement jumbotron
      const jumbotron = data.find((ad) => ad.placement === "jumbotron");
      if (jumbotron) setBannerAd(jumbotron);

      // ambil iklan placement banner
      const banner = data.find((ad) => ad.placement === "banner");
      if (banner) setBannerImageAd(banner);
    } catch (err) {
      console.error("Error fetching advertisement:", err);
    }
  }

  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 scrollRef = useRef<HTMLDivElement>(null);

  const scrollLeft = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: -240, behavior: "smooth" });
    }
  };

  const scrollRight = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: 240, behavior: "smooth" });
    }
  };
  return (
    <section className="max-w-[1600px] px-4 lg:mx-auto py-8 flex flex-col md:flex-wrap lg:flex-row justify-between gap-6 lg:px-0">
      <aside className="w-full md:w-full lg:w-full xl:w-[352px] space-y-4 shrink-0">
        <Card className="rounded-none px-4 py-4">
          <h2 className="text-lg font-semibold border-b pb-2">
            Berita Pilihan
          </h2>
          <ul className="space-y-4">
            {articles.map((news, i) => (
              <li key={i}>
                <Link
                  className="flex gap-3 items-start"
                  href={`/details/${news?.slug}`}
                >
                  <Image
                    src={news?.thumbnailUrl as string}
                    width={100}
                    height={71}
                    alt={news.title}
                    className="w-[100px] h-[71px] object-cover"
                  />

                  <p className="text-sm leading-snug font-semibold px-2">
                    {news.title}
                  </p>
                </Link>
              </li>
            ))}
          </ul>
        </Card>
        <Card className="rounded-none px-4 py-4">
          <h2 className="text-lg font-semibold border-b ">Berita Opini</h2>
          <ul className="space-y-3 ">
            {articles.map((news, i) => (
              <li key={i}>
                <Link
                  className="flex items-start gap-2 text-sm font-medium border-b"
                  href={`/details/${news?.slug}`}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                  >
                    <g
                      fill="none"
                      // fill-rule="evenodd"
                    >
                      <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                      <path
                        fill="currentColor"
                        d="M5.669 4.76a1.47 1.47 0 0 1 2.04-1.177c1.062.454 3.442 1.533 6.462 3.276c3.021 1.744 5.146 3.267 6.069 3.958c.788.591.79 1.763.001 2.356c-.914.687-3.013 2.19-6.07 3.956c-3.06 1.766-5.412 2.832-6.464 3.28c-.906.387-1.92-.2-2.038-1.177c-.138-1.142-.396-3.735-.396-7.237c0-3.5.257-6.092.396-7.235"
                      />
                    </g>
                  </svg>
                  {news.title}
                </Link>
              </li>
            ))}
          </ul>
        </Card>

        <Card className="rounded-none px-4 py-4">
          <h2 className="text-lg font-semibold border-b pb-2">
            Berita Populer
          </h2>
          <div className="space-y-4 ">
            <div>
              <Link href={`/details/${articles[0]?.slug}`}>
                <div className="relative">
                  <img
                    src={articles[0]?.thumbnailUrl}
                    alt={articles[0]?.title}
                    className="w-full h-auto object-cover"
                  />
                  <span className="absolute bottom-1 left-1 bg-black text-white text-xs px-2 py-1">
                    {articles[0]?.categories?.[0]?.title || "TANPA KATEGORI"}
                  </span>
                </div>
                <h3 className="text-base font-bold mt-2">
                  {articles[0]?.title}
                </h3>
                <p className="text-xs text-[#A0A0A0] mt-1 flex items-center gap-1">
                  {" "}
                  <span className="text-black">
                    {articles[0]?.createdByName}{" "}
                  </span>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                  >
                    <g fill="none">
                      <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                      <path
                        fill="currentColor"
                        d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2m0 2a8 8 0 1 0 0 16a8 8 0 0 0 0-16m0 2a1 1 0 0 1 .993.883L13 7v4.586l2.707 2.707a1 1 0 0 1-1.32 1.497l-.094-.083l-3-3a1 1 0 0 1-.284-.576L11 12V7a1 1 0 0 1 1-1"
                      />
                    </g>
                  </svg>{" "}
                  {new Date(articles[0]?.createdAt).toLocaleDateString(
                    "id-ID",
                    {
                      day: "2-digit",
                      month: "long",
                      year: "numeric",
                    }
                  )}
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                    />
                  </svg>
                  0
                </p>
                <p className="text-sm font-serif text-[#A0A0A0] mt-3 line-clamp-3">
                  {articles[0]?.description}
                </p>
              </Link>
            </div>

            {articles.slice(1).map((item, i) => (
              <div key={i}>
                <Link
                  className="flex items-start gap-3"
                  href={`/details/${item?.slug}`}
                >
                  <img
                    src={item.thumbnailUrl}
                    alt={item.title}
                    className="w-24 h-16 object-cover"
                  />
                  <p className="text-sm font-semibold">{item.title}</p>
                </Link>
              </div>
            ))}
          </div>
        </Card>
        <div className="relative w-auto max-w-full h-[300px] overflow-hidden flex items-center mx-auto border my-6 rounded">
          {bannerAd ? (
            <a
              href={bannerAd.redirectLink}
              target="_blank"
              rel="noopener noreferrer"
              className="block w-full"
            >
              <div className="relative w-full h-[350px] flex justify-center">
                <Image
                  src={bannerAd.contentFileUrl}
                  alt={bannerAd.title || "Iklan Banner"}
                  width={1200} // ukuran dasar untuk responsive
                  height={350}
                  className="object-cover w-full h-full"
                />
              </div>
            </a>
          ) : (
            <Image
              src="/kolom.png"
              alt="Berita Utama"
              width={1200}
              height={188}
              className="object-contain w-full h-[188px]"
            />
          )}
        </div>
      </aside>

      <main className="w-full md:w-full lg:w-full xl:w-[655px] space-y-6 shrink-0">
        <div className="flex items-center gap-1 px-4 py-4 bg-white border">
          <button
            onClick={scrollLeft}
            className="flex items-center justify-center w-8 h-24 border rounded hover:bg-gray-100"
          >
            <span className="text-xl font-bold text-gray-700">&lt;</span>
          </button>

          <div
            ref={scrollRef}
            className="flex gap-2 overflow-hidden w-[600px] scroll-smooth"
          >
            {articles.length > 0 ? (
              articles.map((article) => (
                <div key={article.id}>
                  <Link
                    className="flex-shrink-0 flex items-start gap-3 w-[188px]"
                    href={`/details/${article?.slug}`}
                  >
                    <img
                      src={article.thumbnailUrl || "/placeholder.jpg"}
                      alt={article.title}
                      className="w-14 h-14 object-cover rounded"
                    />
                    <p className="text-xs font-medium w-[150px] line-clamp-3">
                      {article.title}
                    </p>
                  </Link>
                </div>
              ))
            ) : (
              <p className="text-gray-500 text-sm px-2">Loading...</p>
            )}
          </div>

          <button
            onClick={scrollRight}
            className="flex items-center justify-center w-8 h-24 border rounded hover:bg-gray-100"
          >
            <span className="text-xl font-bold text-gray-700">&gt;</span>
          </button>
        </div>
        <Card className="border shadow-sm bg-white rounded-none gap-1 py-0">
          {articles.length > 0 ? (
            articles.map((article) => (
              <div key={article.id}>
                <Link href={`/details/${article?.slug}`}>
                  <img
                    src={article.thumbnailUrl || "/komjen-pol.jpg"}
                    alt={article.title}
                    className="w-full h-64 object-cover mb-4"
                  />
                  <div className="p-8">
                    <p className="text-xs text-gray-500 uppercase mb-1">
                      {article.categories?.map((cat) => cat.title).join(", ") ||
                        "Beranda"}
                    </p>
                    <h1 className="text-xl font-bold mt-1">{article.title}</h1>
                    <p className="text-[10px] md:text-sm text-gray-500 mt-1 flex items-center gap-3">
                      BY{" "}
                      <span className="text-black font-semibold text-[10px] md:text-sm">
                        {article.createdByName}
                      </span>{" "}
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="16"
                        height="16"
                        viewBox="0 0 24 24"
                      >
                        <path
                          fill="currentColor"
                          d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2m0 2a8 8 0 1 0 0 16a8 8 0 0 0 0-16m0 2a1 1 0 0 1 .993.883L13 7v4.586l2.707 2.707a1 1 0 0 1-1.32 1.497l-.094-.083l-3-3a1 1 0 0 1-.284-.576L11 12V7a1 1 0 0 1 1-1"
                        />
                      </svg>{" "}
                      {new Date(article.createdAt).toLocaleDateString("id-ID")}
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="h-4 w-4"
                        fill="none"
                        viewBox="0 0 24 24"
                        stroke="currentColor"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
                        />
                      </svg>
                      0
                    </p>
                    <p className="text-sm text-[#666666] mt-2 line-clamp-3">
                      {article.description}
                    </p>
                    <button className="mt-4 text-xs w-6/12 md:w-3/12 border px-3 hover:bg-gray-100 transition py-2">
                      READ MORE
                    </button>
                  </div>
                </Link>
              </div>
            ))
          ) : (
            <p className="p-8 text-gray-500">Tidak ada artikel</p>
          )}
        </Card>

        <div className="relative my-5 h-[125px] overflow-hidden flex items-center mx-auto border">
          {bannerImageAd ? (
            <a
              href={bannerImageAd.redirectLink}
              target="_blank"
              rel="noopener noreferrer"
              className="w-full h-full relative"
            >
              <Image
                src={bannerImageAd.contentFileUrl}
                alt={bannerImageAd.title || "Iklan Banner"}
                fill
                className="object-cover"
              />
            </a>
          ) : (
            <Image
              src="/image-kolom.png"
              alt="Banner Default"
              fill
              className="object-cover"
            />
          )}
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {articles.map((news, i) => (
            <div
              key={i}
              className="bg-white shadow-md rounded-none overflow-hidden border"
            >
              <Link
                className="bg-white shadow-md rounded-none overflow-hidden border"
                href={`/details/${news?.slug}`}
              >
                <div className="relative">
                  <img
                    src={news?.thumbnailUrl || "/komjen-pol.jpg"}
                    alt={news.title}
                    className="w-full h-[223px] object-cover"
                  />
                  <span className="absolute bottom-0 left-1/2 -translate-x-1/2 bg-black text-white text-[10px] px-2 py-[2px] rounded-none uppercase">
                    {news?.categories?.[0]?.title || "TANPA KATEGORI"}
                  </span>
                </div>
                <div className="p-4 text-center">
                  <h3 className="text-lg font-semibold text-gray-900 mb-3 leading-snug px-9">
                    {news.title}
                  </h3>
                  <div className="flex flex-row items-center justify-center text-gray-500 gap-1">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                    >
                      <g fill="none">
                        <path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z" />
                        <path
                          fill="currentColor"
                          d="M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12S6.477 2 12 2m0 2a8 8 0 1 0 0 16a8 8 0 0 0 0-16m0 2a1 1 0 0 1 .993.883L13 7v4.586l2.707 2.707a1 1 0 0 1-1.32 1.497l-.094-.083l-3-3a1 1 0 0 1-.284-.576L11 12V7a1 1 0 0 1 1-1"
                        />
                      </g>
                    </svg>{" "}
                    <p className="text-xs text-gray-400">{news.createdAt}</p>
                  </div>
                </div>
              </Link>
            </div>
          ))}
        </div>
        <Card className="px-5 py-5 rounded-none">
          <h2 className="text-sm font-semibold border-b pb-1 border-black inline-block">
            Berita Utama
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
            {articles.map((news, i) => (
              <div key={i}>
                <Link className="flex gap-4" href={`/details/${news?.slug}`}>
                  <img
                    src={news.thumbnailUrl}
                    alt={news.title}
                    className="w-[100px] h-[70px] object-cover flex-shrink-0"
                  />
                  <p className="text-sm font-semibold text-gray-900 hover:underline leading-snug">
                    {news.title}
                  </p>
                </Link>
              </div>
            ))}
          </div>
        </Card>

        <div className="relative my-5 h-[125px] overflow-hidden flex items-center mx-auto border">
          {bannerImageAd ? (
            <a
              href={bannerImageAd.redirectLink}
              target="_blank"
              rel="noopener noreferrer"
              className="w-full h-full relative"
            >
              <Image
                src={bannerImageAd.contentFileUrl}
                alt={bannerImageAd.title || "Iklan Banner"}
                fill
                className="object-cover"
              />
            </a>
          ) : (
            <Image
              src="/image-kolom.png"
              alt="Banner Default"
              fill
              className="object-cover"
            />
          )}
        </div>

        <div className="space-y-4">
          <Card className="px-5 py-5 rounded-none">
            <h2 className="text-sm font-semibold border-b pb-1 border-black inline-block">
              Berita Pilihan
            </h2>

            {articles.map((recentNews, i) => (
              <div key={i}>
                <Link
                  className="flex flex-col sm:flex-row gap-4 mt-4"
                  href={`/details/${recentNews?.slug}`}
                >
                  <img
                    src={recentNews.thumbnailUrl || "/komjen-pol.jpg"}
                    alt={recentNews.title}
                    className="w-full sm:w-[220px] h-[157px] object-cover"
                  />
                  <div className="flex-1">
                    <h3 className="text-base font-bold">{recentNews.title}</h3>
                    <p className="text-xs text-gray-500 mt-1 flex flex-wrap items-center gap-2 mb-3">
                      BY{" "}
                      <span className="font-semibold text-black">
                        {recentNews.createdByName}
                      </span>
                      <Clock className="w-3 h-3" />
                      {recentNews.createdAt}
                      <MessageCircle className="w-3 h-3" />0
                    </p>
                    <p className="text-sm text-gray-600 line-clamp-3">
                      {recentNews.description}
                    </p>
                  </div>
                </Link>
              </div>
            ))}

            <button className="mt-4 text-xs w-full border px-3 hover:bg-gray-100 transition py-2">
              LOAD MORE
            </button>
          </Card>

          <div className="relative my-5 h-[125px] overflow-hidden flex items-center mx-auto border">
            {bannerImageAd ? (
              <a
                href={bannerImageAd.redirectLink}
                target="_blank"
                rel="noopener noreferrer"
                className="w-full h-full relative"
              >
                <Image
                  src={bannerImageAd.contentFileUrl}
                  alt={bannerImageAd.title || "Iklan Banner"}
                  fill
                  className="object-cover"
                />
              </a>
            ) : (
              <Image
                src="/image-kolom.png"
                alt="Banner Default"
                fill
                className="object-cover"
              />
            )}
          </div>
        </div>
      </main>

      <aside className="w-full md:w-full lg:w-full xl:w-[312px] space-y-6 shrink-0">
        {articles.map((news, i) => (
          <div className="border" key={i}>
            <Link
              className="rounded-none overflow-hidden bg-white shadow-sm p-0 gap-1"
              href={`/details/${news?.slug}`}
            >
              <div className="relative">
                {news?.thumbnailUrl && (
                  <img
                    src={news?.thumbnailUrl}
                    alt={news.title}
                    className="w-full h-[224px] object-cover"
                  />
                )}
                {news?.categories?.[0]?.title && (
                  <span className="absolute top-2 left-2 bg-black text-white text-[10px] px-2 py-1 rounded-none uppercase tracking-wide">
                    {news?.categories?.[0]?.title}
                  </span>
                )}
              </div>
              <div className="p-4">
                <h3 className="text-base font-bold leading-snug">
                  {news.title}
                </h3>
                {news.createdByName && news.createdAt && (
                  <p className="text-xs text-gray-500 mt-2 font-medium mb-4">
                    BY <span className="text-black">{news.createdByName}</span>{" "}
                    · {news.createdAt}
                  </p>
                )}
                {news.description && (
                  <p className="text-sm text-gray-600 mt-2 line-clamp-5">
                    {news.description}
                  </p>
                )}
              </div>
            </Link>
          </div>
        ))}
        <div className="relative w-auto max-w-full h-[300px] overflow-hidden flex items-center mx-auto border my-6 rounded">
          {bannerAd ? (
            <a
              href={bannerAd.redirectLink}
              target="_blank"
              rel="noopener noreferrer"
              className="block w-full"
            >
              <div className="relative w-full h-[350px] flex justify-center">
                <Image
                  src={bannerAd.contentFileUrl}
                  alt={bannerAd.title || "Iklan Banner"}
                  width={1200} // ukuran dasar untuk responsive
                  height={350}
                  className="object-cover w-full h-full"
                />
              </div>
            </a>
          ) : (
            <Image
              src="/kolom.png"
              alt="Berita Utama"
              width={1200}
              height={188}
              className="object-contain w-full h-[188px]"
            />
          )}
        </div>
      </aside>
    </section>
  );
}
