"use client";

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useState,
  type ReactNode,
} from "react";
import { useSearchParams } from "next/navigation";
import { Menu } from "lucide-react";
import FloatingMenuNews from "@/components/landing-page/floating-news";
import Footer from "@/components/landing-page/footer";
import {
  fetchPublishedArticles,
  type PublicArticle,
} from "@/lib/articles-public";
import PublicArticleCard from "@/components/content-type/public-article-card";

const PAGE_SIZE = 12;

type Config = {
  typeId: number;
  breadcrumb: string;
};

type Props = {
  config: Config;
  sidebar: ReactNode;
};

export default function ArticleTypeFilterPage({ config, sidebar }: Props) {
  const searchParams = useSearchParams();
  const q = searchParams.get("q")?.trim() ?? "";
  const tag = searchParams.get("tag")?.trim() ?? "";

  const [openFilter, setOpenFilter] = useState(false);
  const [page, setPage] = useState(1);
  const [sort, setSort] = useState<"popular" | "latest">("latest");
  const [items, setItems] = useState<PublicArticle[]>([]);
  const [totalPage, setTotalPage] = useState(1);
  const [totalCount, setTotalCount] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    const sortBy = sort === "popular" ? "view_count" : "created_at";
    const res = await fetchPublishedArticles(
      {
        typeId: config.typeId,
        limit: PAGE_SIZE,
        page,
        sortBy,
        sort: "desc",
        title: q || undefined,
        tags: tag || undefined,
      },
      { mode: "client" },
    );
    setItems(res?.items ?? []);
    const meta = res?.meta as
      | { totalPage?: number; count?: number }
      | undefined;
    setTotalPage(Math.max(1, meta?.totalPage ?? 1));
    setTotalCount(typeof meta?.count === "number" ? meta.count : null);
    setLoading(false);
  }, [config.typeId, page, sort, q, tag]);

  useLayoutEffect(() => {
    setPage(1);
  }, [q, tag, config.typeId]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <div className="relative min-h-screen bg-white font-[family-name:var(--font-geist-sans)]">
      <section className="min-h-screen py-10">
        <div className="container mx-auto px-6">
          <div className="mb-6 flex items-center justify-between lg:hidden">
            <button
              type="button"
              onClick={() => setOpenFilter(true)}
              className="inline-flex items-center gap-2 rounded-lg border px-3 py-2 text-sm"
            >
              <Menu className="h-4 w-4" />
              Filter
            </button>
          </div>

          <div className="grid grid-cols-1 gap-8 lg:grid-cols-[280px_1fr]">
            <div className="hidden lg:block">{sidebar}</div>

            {openFilter && (
              <div className="fixed inset-0 z-50 bg-black/40">
                <div className="absolute top-0 left-0 h-full w-[280px] overflow-y-auto bg-white p-6">
                  {sidebar}
                  <button
                    type="button"
                    onClick={() => setOpenFilter(false)}
                    className="mt-4 text-sm text-[#966314]"
                  >
                    Tutup
                  </button>
                </div>
              </div>
            )}

            <div>
              <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <div className="text-sm text-gray-500">
                  {config.breadcrumb} &nbsp; &gt; &nbsp;
                  <span className="font-semibold text-black">Lihat Semua</span>
                  <span className="ml-3 font-semibold text-black">{"|"}</span>
                  <span className="ml-4 text-gray-400">
                    {totalCount != null
                      ? `Terdapat ${totalCount} konten`
                      : loading
                        ? "Memuat…"
                        : `Terdapat ${items.length} konten`}
                  </span>
                </div>

                <div className="flex flex-wrap items-center gap-4">
                  <span className="text-sm">Urutkan:</span>
                  <select
                    value={sort}
                    onChange={(e) => {
                      setSort(e.target.value as "popular" | "latest");
                      setPage(1);
                    }}
                    className="rounded-md border px-3 py-2 text-sm"
                  >
                    <option value="latest">Terbaru</option>
                    <option value="popular">Terpopuler</option>
                  </select>
                  <FloatingMenuNews />
                </div>
              </div>

              {loading ? (
                <p className="text-center text-muted-foreground">Memuat…</p>
              ) : items.length === 0 ? (
                <p className="text-center text-muted-foreground">
                  Belum ada konten yang dipublikasikan.
                </p>
              ) : (
                <div className="grid grid-cols-1 gap-6 md:grid-cols-2 xl:grid-cols-3">
                  {items.map((article) => (
                    <PublicArticleCard key={article.id} article={article} />
                  ))}
                </div>
              )}

              {totalPage > 1 && !loading && items.length > 0 ? (
                <div className="mt-12 flex flex-wrap items-center justify-center gap-2 text-sm">
                  <button
                    type="button"
                    disabled={page <= 1}
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    className="rounded border bg-white px-3 py-1 disabled:opacity-40"
                  >
                    Sebelumnya
                  </button>
                  <span className="px-2 text-gray-600">
                    Halaman {page} / {totalPage}
                  </span>
                  <button
                    type="button"
                    disabled={page >= totalPage}
                    onClick={() =>
                      setPage((p) => Math.min(totalPage, p + 1))
                    }
                    className="rounded border bg-white px-3 py-1 disabled:opacity-40"
                  >
                    Selanjutnya
                  </button>
                </div>
              ) : null}
            </div>
          </div>
        </div>
      </section>
      <Footer />
    </div>
  );
}
