import Image from "next/image";
import Link from "next/link";
import { PageContainer } from "@/components/layout/page-container";
import { BlogCard } from "@/components/ui/blog-card";
import { EmptyStateCard } from "@/components/ui/empty-state-card";
import { Pagination } from "@/components/ui/pagination";
import { detonexFigmaAssets } from "@/lib/detonex-figma";
import { cn } from "@/lib/cn";
import type { StorefrontBlogArchivePage } from "@/types/storefront";

function buildBlogArchiveHref({
  page,
  query,
  category,
}: {
  page?: number;
  query?: string;
  category?: string;
}) {
  const params = new URLSearchParams();

  if (page && page > 1) {
    params.set("page", String(page));
  }

  if (query?.trim()) {
    params.set("q", query.trim());
  }

  if (category?.trim()) {
    params.set("category", category.trim());
  }

  const serialized = params.toString();
  return serialized ? `/blog?${serialized}` : "/blog";
}

export function BlogArchiveSection({
  archive,
}: {
  archive: StorefrontBlogArchivePage;
}) {
  const currentCategoryLabel =
    archive.categories.find((category) => category.slug === archive.currentCategorySlug)
      ?.name || "Sve kategorije";

  return (
    <section className="bg-white">
      <PageContainer className="pt-[60px] pb-20">
        <div className="space-y-[42px]">
          <div className="space-y-[42px]">
            <h1 className="text-[38px] font-bold leading-[1.2] tracking-[-0.03em] text-primary">
              Savjeti i novosti
            </h1>

            <div className="flex flex-col justify-between gap-4 md:flex-row md:items-center">
              <details className="group relative w-full md:w-[186px]">
                <summary className="flex h-[45px] cursor-pointer list-none items-center justify-between rounded-[6px] border border-line bg-white px-5 text-[16px] font-bold tracking-[-0.02em] text-primary marker:content-none">
                  <span>{currentCategoryLabel}</span>
                  <Image
                    src={detonexFigmaAssets.icons.chevronDown}
                    alt=""
                    width={18}
                    height={18}
                    className="size-[18px] transition-transform group-open:rotate-180"
                  />
                </summary>

                <div className="absolute left-0 top-[calc(100%+8px)] z-20 w-full rounded-[8px] border border-line bg-white p-2 shadow-[0_20px_40px_rgba(32,32,33,0.08)]">
                  <Link
                    href={buildBlogArchiveHref({ query: archive.query })}
                    className={cn(
                      "block rounded-[6px] px-3 py-2 text-[14px] font-medium tracking-[-0.02em] text-primary transition-colors hover:bg-muted-surface",
                      !archive.currentCategorySlug ? "bg-muted-surface" : "",
                    )}
                  >
                    Sve kategorije
                  </Link>
                  {archive.categories.map((category) => (
                    <Link
                      key={category.id}
                      href={buildBlogArchiveHref({
                        query: archive.query,
                        category: category.slug,
                      })}
                      className={cn(
                        "block rounded-[6px] px-3 py-2 text-[14px] font-medium tracking-[-0.02em] text-primary transition-colors hover:bg-muted-surface",
                        archive.currentCategorySlug === category.slug
                          ? "bg-muted-surface"
                          : "",
                      )}
                    >
                      {category.name}
                    </Link>
                  ))}
                </div>
              </details>

              <form action="/blog" className="flex h-12 w-full items-center rounded-[6px] border border-line bg-white md:w-[400px]">
                {archive.currentCategorySlug ? (
                  <input type="hidden" name="category" value={archive.currentCategorySlug} />
                ) : null}
                <input
                  type="search"
                  name="q"
                  defaultValue={archive.query}
                  placeholder="Pretraži blog objave"
                  className="h-full flex-1 appearance-none border-0 bg-transparent px-6 text-[14px] font-medium tracking-[-0.02em] text-primary outline-none placeholder:text-primary/65 [&::-webkit-search-cancel-button]:hidden [&::-webkit-search-decoration]:hidden [&::-webkit-search-results-button]:hidden [&::-webkit-search-results-decoration]:hidden"
                />
                <button
                  type="submit"
                  aria-label="Pretraži blog"
                  className="mr-6 inline-flex size-5 items-center justify-center"
                >
                  <Image
                    src={detonexFigmaAssets.icons.search}
                    alt=""
                    width={20}
                    height={20}
                    className="size-5"
                  />
                </button>
              </form>
            </div>
          </div>

          {archive.posts.length > 0 ? (
            <>
              <div className="grid gap-x-5 gap-y-8 lg:grid-cols-3">
                {archive.posts.map((post) => (
                  <BlogCard key={post.id} post={post} />
                ))}
              </div>

              {archive.totalPages > 1 ? (
                <div className="pt-[10px]">
                  <Pagination
                    currentPage={archive.currentPage}
                    totalPages={archive.totalPages}
                    hrefBuilder={(page) =>
                      buildBlogArchiveHref({
                        page,
                        query: archive.query,
                        category: archive.currentCategorySlug,
                      })
                    }
                  />
                </div>
              ) : null}
            </>
          ) : (
            <EmptyStateCard
              title="Nema blog objava za prikaz"
              description="Kad dodaš objave u WordPressu, ovdje će se pojaviti archive popis s kategorijama, pretragom i paginacijom."
            />
          )}
        </div>
      </PageContainer>
    </section>
  );
}
