"use client";

import {
  Facebook,
  Instagram,
  RefreshCcwIcon,
  ThumbsUpIcon,
  Twitter,
  UserRoundPlus,
  Youtube,
} from "lucide-react";
import Image from "next/image";
import { useEffect, useState } from "react";
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 News() {
  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,
  });

  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("Failed to fetch articles:", error);
    }
  }

  function truncateText(text: string, wordLimit: number) {
    const words = text.split(" ");
    if (words.length <= wordLimit) return text;
    return words.slice(0, wordLimit).join(" ") + "...";
  }

  return (
    <section className="bg-white py-10 px-4 md:px-10 w-full">
      <div className="max-w-screen-xl mx-auto flex flex-col lg:flex-row lg:justify-between gap-5">
        {/* Left: News Section */}
        <div className="w-full lg:w-2/3">
          <div className="flex flex-row items-center pb-2 mb-3 gap-4">
            <h2 className="text-lg font-bold ">BERITA TERKINI</h2>
            <div className="flex-grow border-t-3 border-gray-300 rounded-md"></div>
          </div>

          <div className="space-y-10">
            {articles.map((item) => (
              <div
                key={item.id}
                className="flex flex-col md:flex-row gap-4 pb-6"
              >
                <div className="w-full md:w-[250px]">
                  <Image
                    src={item.thumbnailUrl || "/dummy.jpg"}
                    alt={item.title}
                    width={250}
                    height={180}
                    className="w-full h-auto object-cover"
                  />
                </div>

                <div className="flex-1">
                  <span className="inline-block bg-black text-white text-xs px-2 py-1 mb-2">
                    {item.categoryName || "Berita Terkini"}
                  </span>
                  <h3 className="font-semibold text-xl font-serif mb-2">
                    {item.title}
                  </h3>
                  <p className="text-xs text-[#999999] mb-2 flex items-center gap-2">
                    by {item.createdByName || "admin"}{" "}
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                    >
                      <g fill="none">
                        <path d="M0 0h24v24H0z" />
                        <path
                          fill="currentColor"
                          d="M12 8v4l3 3l1-1l-2.5-2.5V8zM12 2a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2m0 18a8 8 0 1 1 8-8a8.009 8.009 0 0 1-8 8"
                        />
                      </g>
                    </svg>
                    {new Date(item.createdAt).toLocaleDateString("id-ID", {
                      day: "numeric",
                      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-[#999999] text-sm font-serif">
                    {truncateText(item.description, 50)}
                  </p>
                </div>
              </div>
            ))}
          </div>

          {/* Load more button */}
          <div className="flex justify-center">
            {page < totalPage && (
              <button
                className="flex items-center justify-center gap-2 px-6 py-2 text-sm bg-black text-white hover:bg-black hover:text-white transition w-[350px] text-center"
                onClick={() => setPage((prev) => prev + 1)}
              >
                Load More Posts
                <RefreshCcwIcon className="w-4 h-4" />
              </button>
            )}
          </div>

          {/* Banner */}
          <div className="relative my-5 max-w-full h-[125px] overflow-hidden flex items-center mx-auto border">
            <Image
              src="/image-kolom.png"
              alt="Berita Utama"
              fill
              className="object-cover"
            />
          </div>
        </div>

        {/* Right Sidebar */}
        <aside className="w-full lg:w-[340px]">
          <div className="border p-4 shadow-sm rounded-md">
            <div className="flex flex-row items-center pb-2 mb-4 gap-4">
              <h3 className="font-semibold text-sm">SOCIAL NETWORKS</h3>
              <div className="flex-grow border-t-3 border-gray-300 rounded-md"></div>
            </div>
            <ul className="space-y-3 text-sm">
              <li className="flex items-center justify-between border px-3 py-2 hover:bg-gray-100 transition rounded">
                <span className="flex items-center gap-2 text-gray-700">
                  <Facebook className="text-black" />
                  FACEBOOK
                </span>
                <span className="flex items-center gap-1 text-gray-500 text-xs">
                  <ThumbsUpIcon size={15} /> LIKE
                </span>
              </li>
              <li className="flex items-center justify-between border px-3 py-2 hover:bg-gray-100 transition rounded">
                <span className="flex items-center gap-2 text-gray-700">
                  <Twitter className="text-black" />
                  TWITTER
                </span>
                <span className="flex items-center gap-1 text-gray-500 text-xs">
                  <UserRoundPlus size={15} /> FOLLOW
                </span>
              </li>
              <li className="flex items-center justify-between border px-3 py-2 hover:bg-gray-100 transition rounded">
                <span className="flex items-center gap-2 text-gray-700">
                  <Instagram className="text-black" />
                  INSTAGRAM
                </span>
                <span className="flex items-center gap-1 text-gray-500 text-xs">
                  <UserRoundPlus size={15} /> FOLLOW
                </span>
              </li>
              <li className="flex items-center justify-between border px-3 py-2 hover:bg-gray-100 transition rounded">
                <span className="flex items-center gap-2 text-gray-700">
                  <p className=" bg-black rounded-full text-white w-[20px] text-center ml-1">
                    P
                  </p>
                  PINTEREST
                </span>
                <span className="flex items-center gap-1 text-gray-500 text-xs">
                  <UserRoundPlus size={15} /> FOLLOW
                </span>
              </li>
              <li className="flex items-center justify-between border px-3 py-2 hover:bg-gray-100 transition rounded">
                <span className="flex items-center gap-2 text-gray-700">
                  <Youtube className="text-black" />
                  YOUTUBE
                </span>
                <span className="flex items-center gap-1 text-gray-500 text-xs">
                  <UserRoundPlus size={15} /> SUBSCRIBE
                </span>
              </li>
            </ul>
          </div>

          {/* Sidebar banners */}
          <div className="relative w-[1111px] max-w-full h-[300px] overflow-hidden flex items-center mx-auto border my-6 rounded">
            <Image
              src="/kolom.png"
              alt="Berita Utama"
              fill
              className="object-contain rounded"
            />
          </div>
          <div className="relative w-[1111px] max-w-full h-[300px] overflow-hidden flex items-center mx-auto border my-6 rounded">
            <Image
              src="/kolom.png"
              alt="Berita Utama"
              fill
              className="object-contain rounded"
            />
          </div>
        </aside>
      </div>
    </section>
  );
}
