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 "";
  }
}

export type PublicPostsListProps = {
  items: PublicPostListItem[];
  emptyMessage?: ReactNode;
  showCategoryLabel?: boolean;
  pagination?: {
    page: number;
    totalPages: number;
    hrefForPage: (page: number) => string;
  };
};

export function PublicPostsList({
  items,
  emptyMessage,
  showCategoryLabel = true,
  pagination,
}: PublicPostsListProps) {
  const defaultEmpty = (
    <>
      Sổ còn im — chưa có thiên nào, hoặc chưa nối{" "}
      <code className="rounded-md bg-black/35 px-2 py-0.5 text-amber-200/75">
        NEXT_PUBLIC_API_BASE_URL
      </code>{" "}
      tới nguồn chữ.
    </>
  );

  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 text-sm leading-relaxed text-stone-500">
              {emptyMessage ?? defaultEmpty}
            </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">
                          {showCategoryLabel ? (
                            <p className="ctkp-eyebrow tracking-[0.32em]">
                              {post.category.name}
                            </p>
                          ) : null}
                          {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>

      {pagination && pagination.totalPages > 1 ? (
        <nav
          className="mt-16 flex items-center justify-between border-t border-amber-950/25 pt-10 text-sm sm:mt-20 sm:pt-12"
          aria-label="Phân trang"
        >
          {pagination.page > 1 ? (
            <Link
              href={pagination.hrefForPage(pagination.page - 1)}
              className="rounded-lg border border-[#9a7b4a]/38 bg-black/25 px-5 py-2.5 text-amber-100/85 transition-colors duration-200 ease-out hover:border-[#b8975e]/45 hover:text-amber-50"
            >
              ← Trước
            </Link>
          ) : (
            <span />
          )}
          <span className="text-stone-500">
            Trang {pagination.page} / {pagination.totalPages}
          </span>
          {pagination.page < pagination.totalPages ? (
            <Link href={pagination.hrefForPage(pagination.page + 1)} className="ctkp-btn-ghost">
              Sau →
            </Link>
          ) : (
            <span />
          )}
        </nav>
      ) : null}
    </>
  );
}
