import Link from "next/link";
import type { BlogPagination } from "@/types";

interface PaginationProps {
  basePath: string;
  pagination: BlogPagination;
  searchQuery?: string;
}

export default function Pagination({ basePath, pagination, searchQuery }: PaginationProps) {
  const { current, total } = pagination;

  if (total <= 1) return null;

  const makeHref = (page: number) => {
    const params = new URLSearchParams();
    if (page > 1) params.set("page", page.toString());
    if (searchQuery) params.set("search", searchQuery);
    const qs = params.toString();
    return qs ? `${basePath}?${qs}` : basePath;
  };

  const pages: number[] = [];
  for (let i = 1; i <= total; i++) {
    if (i === 1 || i === total || (i >= current - 2 && i <= current + 2)) {
      pages.push(i);
    }
  }

  const items: (number | "...")[] = [];
  for (let i = 0; i < pages.length; i++) {
    const page = pages[i];
    items.push(page);
    if (i < pages.length - 1 && pages[i + 1] !== page + 1) {
      items.push("...");
    }
  }

  return (
    <nav aria-label="Blog pagination" className="mt-4">
      <ul className="pagination justify-content-center hai-pagination">
        {current > 1 && (
          <li className="page-item">
            <Link className="page-link" href={makeHref(current - 1)} aria-label="Previous page">
              <i className="fa-solid fa-arrow-left" aria-hidden="true"></i>
            </Link>
          </li>
        )}

        {items.map((item, idx) =>
          item === "..." ? (
            <li key={`ellipsis-${idx}`} className="page-item disabled">
              <span className="page-link">...</span>
            </li>
          ) : (
            <li key={item} className={`page-item ${item === current ? "active" : ""}`}>
              {item === current ? (
                <span className="page-link">{item}</span>
              ) : (
                <Link className="page-link" href={makeHref(item as number)}>
                  {item}
                </Link>
              )}
            </li>
          ),
        )}

        {current < total && (
          <li className="page-item">
            <Link className="page-link" href={makeHref(current + 1)} aria-label="Next page">
              <i className="fa-solid fa-arrow-right" aria-hidden="true"></i>
            </Link>
          </li>
        )}
      </ul>
    </nav>
  );
}

