import type { ReactNode } from "react";
import Link from "next/link";

import { absoluteFromApiPath } from "@/lib/api";
import type { PublicPostListItem } from "@/lib/posts";
import {
  PostFeaturedImage,
  PostFeaturedPlaceholder,
  postFeaturedAspectClass,
} from "@/components/PostFeaturedMedia";

function formatDate(iso: string | null) {
  if (!iso) return "";
  try {
    return new Date(iso).toLocaleDateString("vi-VN", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  } catch {
    return "";
  }
}

type PublicPostArchiveListProps = {
  items: PublicPostListItem[];
  page: number;
  totalPages: number;
  hrefForPage: (page: number) => string;
  /** Short line above the empty body — calmer than a wall of text. */
  emptyTitle?: string;
  emptyMessage: ReactNode;
};

export function PublicPostArchiveList({
  items,
  page,
  totalPages,
  hrefForPage,
  emptyTitle,
  emptyMessage,
}: PublicPostArchiveListProps) {
  return (
    <>
      <section className="mt-14 sm:mt-16 lg:mt-20" aria-label="Danh sách bài viết">
        <ul className="flex flex-col gap-8 sm:gap-10">
          {items.length === 0 ? (
            <li className="rounded-xl border border-dashed border-stone-700/45 bg-[#0c0b0a]/55 px-8 py-16 text-center sm:px-10 sm:py-20">
              {emptyTitle ? (
                <p className="font-ctkp-display text-lg font-semibold tracking-tight text-stone-200 sm:text-xl">
                  {emptyTitle}
                </p>
              ) : null}
              <div className={`text-sm leading-relaxed text-stone-500 ${emptyTitle ? "mt-4" : ""}`}>
                {emptyMessage}
              </div>
            </li>
          ) : (
            items.map((post) => {
              const img = absoluteFromApiPath(post.featuredImage);
              return (
                <li key={post.id}>
                  <article
                    className="group overflow-hidden rounded-xl border border-stone-800/45 bg-[#0c0b0a]/90 transition-colors duration-200 ease-ctkp hover:border-[#6b5a3a]/32"
                  >
                    <Link
                      href={`/posts/${post.slug}`}
                      className="block min-w-0 sm:flex sm:min-h-[220px] sm:items-stretch"
                    >
                      {img ? (
                        <PostFeaturedImage
                          src={img}
                          alt=""
                          variant="list"
                          className={`${postFeaturedAspectClass} sm:aspect-auto sm:h-full sm:min-h-[220px] sm:w-[min(38%,280px)] sm:self-stretch`}
                          imgClassName="transition-opacity duration-300 ease-ctkp group-hover:opacity-95"
                        />
                      ) : (
                        <PostFeaturedPlaceholder
                          className={`${postFeaturedAspectClass} w-full shrink-0 sm:aspect-auto sm:h-full sm:min-h-[220px] sm:w-[min(38%,280px)] sm:self-stretch sm:border-r sm:border-amber-950/25`}
                        />
                      )}
                      <div className="flex flex-1 flex-col justify-center px-7 py-7 sm:px-10 sm:py-9">
                        <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
                          <p className="ctkp-eyebrow tracking-[0.32em]">
                            {post.category.name}
                          </p>
                          {post.publishedAt ? (
                            <time
                              className="text-[11px] tracking-wide text-amber-200/38"
                              dateTime={post.publishedAt}
                            >
                              {formatDate(post.publishedAt)}
                            </time>
                          ) : null}
                        </div>
                        <h2 className="font-ctkp-display mt-3 text-[1.45rem] font-semibold leading-[1.28] tracking-tight text-stone-100 sm:text-[1.65rem] sm:leading-[1.22]">
                          {post.title}
                        </h2>
                        {post.excerpt ? (
                          <p className="mt-4 line-clamp-3 text-[0.9375rem] leading-[1.72] text-stone-400">
                            {post.excerpt}
                          </p>
                        ) : null}
                      </div>
                    </Link>
                  </article>
                </li>
              );
            })
          )}
        </ul>
      </section>

      {totalPages > 1 ? (
        <nav
          className="mt-12 grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-x-2 gap-y-2 border-t border-amber-950/25 pt-8 text-sm sm:mt-20 sm:gap-x-3 sm:pt-12"
          aria-label="Phân trang"
        >
          <div className="min-w-0 justify-self-start">
            {page > 1 ? (
              <Link
                href={hrefForPage(page - 1)}
                className="inline-flex rounded-lg border border-[#9a7b4a]/38 bg-black/25 px-3 py-2.5 text-amber-100/85 transition-colors duration-200 ease-out hover:border-[#b8975e]/45 hover:text-amber-50 sm:px-5"
              >
                ← Trước
              </Link>
            ) : (
              <span className="inline-block min-h-[2.5rem] min-w-[1px]" aria-hidden />
            )}
          </div>
          <p className="shrink-0 text-center text-xs text-stone-500 tabular-nums sm:text-sm">
            Trang {page} / {totalPages}
          </p>
          <div className="min-w-0 justify-self-end">
            {page < totalPages ? (
              <Link
                href={hrefForPage(page + 1)}
                className="ctkp-btn-ghost inline-flex px-3 py-2.5 sm:px-5"
              >
                Sau →
              </Link>
            ) : (
              <span className="inline-block min-h-[2.5rem] min-w-[1px]" aria-hidden />
            )}
          </div>
        </nav>
      ) : null}
    </>
  );
}
