"use client";

import React from "react";
import { PaginationProps } from "./types";

import { Link } from "@shared/components/link";
import { MaterialIcon } from "@shared/components/material-icon";

const defaultGetPageHref = (page: number) => `?page=${page}`;

export const Pagination: React.FC<PaginationProps> = ({
  currentPage,
  totalPages,
  onPageChange,
  getPageHref = defaultGetPageHref,
  ariaLabel = "Pagination",
}: PaginationProps) => {
  const pageItems = buildPageItems(currentPage, totalPages);

  const navLinkBase =
    "inline-flex items-center justify-center w-9 h-9 rounded-full bg-transparent cursor-pointer transition-colors duration-150 hover:border-text-brand hover:text-text-brand";

  const navLinkDisabled = "opacity-40 pointer-events-none";

  const pageLinkBase =
    "inline-flex items-center justify-center w-9 h-9 rounded-lg text-body2 text-gray-700 bg-transparent border-none cursor-pointer transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900";

  const pageLinkActive = "bg-bg-surface-active font-bold hover:bg-bg-gray-300";

  return (
    <nav
      className="flex items-center justify-center gap-1 px-6 pb-12"
      aria-label={ariaLabel}
    >
      {/* Previous */}
      <Link
        href={currentPage === 1 ? "#" : getPageHref(currentPage - 1)}
        className={`${navLinkBase} ${currentPage === 1 ? navLinkDisabled : ""}`}
        aria-label="Go to previous page"
        aria-disabled={currentPage === 1}
        tabIndex={currentPage === 1 ? -1 : undefined}
        onClick={e => {
          if (currentPage === 1) {
            e.preventDefault();
            return;
          }
          onPageChange?.(currentPage - 1);
        }}
      >
        <MaterialIcon name="chevron_left" size={32} aria-hidden="true" />
      </Link>

      {/* Page numbers */}
      {pageItems.map((item, idx) =>
        item === "..." ? (
          <span
            key={`ellipsis-${idx}`}
            className="inline-flex h-9 w-9 cursor-default items-center justify-center text-body2 text-gray-500"
            aria-hidden="true"
          >
            …
          </span>
        ) : (
          <Link
            key={item}
            href={getPageHref(item)}
            className={`${pageLinkBase} ${item === currentPage ? pageLinkActive : ""}`}
            aria-label={`Go to page ${item}`}
            aria-current={item === currentPage ? "page" : undefined}
            onClick={() => onPageChange?.(item)}
          >
            {item}
          </Link>
        )
      )}

      {/* Next */}
      <Link
        href={currentPage === totalPages ? "#" : getPageHref(currentPage + 1)}
        className={`${navLinkBase} ${currentPage === totalPages ? navLinkDisabled : ""}`}
        aria-label="Go to next page"
        aria-disabled={currentPage === totalPages}
        tabIndex={currentPage === totalPages ? -1 : undefined}
        onClick={e => {
          if (currentPage === totalPages) {
            e.preventDefault();
            return;
          }
          onPageChange?.(currentPage + 1);
        }}
      >
        <MaterialIcon name="chevron_right" size={32} aria-hidden="true" />
      </Link>
    </nav>
  );
};

/** Returns an array of page numbers and ellipsis to render. */
function buildPageItems(current: number, total: number): (number | "...")[] {
  if (total <= 7) {
    return Array.from({ length: total }, (_, i) => i + 1);
  }

  if (current <= 4) {
    return [1, 2, 3, 4, 5, "...", total];
  }

  if (current >= total - 3) {
    return [1, "...", total - 4, total - 3, total - 2, total - 1, total];
  }

  return [1, "...", current - 1, current, current + 1, "...", total];
}
