"use client";

import { ChevronLeft, ChevronRight } from "lucide-react";
import { useRouter } from "next/navigation";

interface PaginationProps {
  currentPage: number;
  lastPage: number;
  perPage: number;
  total: number;
  baseUrl: string;
  onPageChange?: (page: number) => void;
}

export default function Pagination({
  currentPage,
  lastPage,
  perPage,
  total,
  baseUrl,
  onPageChange,
}: PaginationProps) {
  const router = useRouter();

  // Generate page numbers to display
  const getPageNumbers = () => {
    const pages = [];
    const maxPagesToShow = 5;

    if (lastPage <= maxPagesToShow) {
      // Show all pages if there are few pages
      for (let i = 1; i <= lastPage; i++) {
        pages.push(i);
      }
    } else {
      // Always show first page
      pages.push(1);

      // Calculate start and end of page range around current page
      let startPage = Math.max(2, currentPage - 1);
      let endPage = Math.min(lastPage - 1, currentPage + 1);

      // Adjust if we're near the beginning
      if (currentPage <= 3) {
        endPage = Math.min(lastPage - 1, 4);
      }

      // Adjust if we're near the end
      if (currentPage >= lastPage - 2) {
        startPage = Math.max(2, lastPage - 3);
      }

      // Add ellipsis after first page if needed
      if (startPage > 2) {
        pages.push("ellipsis-start");
      }

      // Add middle pages
      for (let i = startPage; i <= endPage; i++) {
        pages.push(i);
      }

      // Add ellipsis before last page if needed
      if (endPage < lastPage - 1) {
        pages.push("ellipsis-end");
      }

      // Always show last page
      if (lastPage > 1) {
        pages.push(lastPage);
      }
    }

    return pages;
  };

  const handlePageClick = (page: number) => {
    if (page === currentPage) return;

    if (onPageChange) {
      onPageChange(page);
    } else {
      // If no onPageChange handler is provided, use URL navigation
      const url = page === 1 ? baseUrl : `${baseUrl}?page=${page}`;
      router.push(url);
    }
  };

  if (lastPage <= 1) return null;

  return (
    <nav className="flex justify-center mt-12" aria-label="Pagination">
      <ul className="inline-flex items-center -space-x-px">
        {/* Previous button */}
        <li>
          <button
            onClick={() => currentPage > 1 && handlePageClick(currentPage - 1)}
            disabled={currentPage === 1}
            className={`flex items-center justify-center px-3 h-10 ml-0 leading-tight rounded-l-lg border ${
              currentPage === 1
                ? "text-gray-300 bg-gray-50 border-gray-200 cursor-not-allowed"
                : "text-gray-500 bg-white border-gray-300 hover:bg-gray-100 hover:text-gray-700"
            }`}
          >
            <span className="sr-only">Previous</span>
            <ChevronLeft className="w-5 h-5" />
          </button>
        </li>

        {/* Page numbers */}
        {getPageNumbers().map((page, index) => {
          if (page === "ellipsis-start" || page === "ellipsis-end") {
            return (
              <li key={`ellipsis-${index}`}>
                <span className="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300">
                  ...
                </span>
              </li>
            );
          }

          return (
            <li key={`page-${page}`}>
              <button
                onClick={() => handlePageClick(page as number)}
                className={`flex items-center justify-center px-4 h-10 leading-tight border ${
                  currentPage === page
                    ? "text-white bg-orange-600 border-orange-600 hover:bg-orange-700"
                    : "text-gray-500 bg-white border-gray-300 hover:bg-gray-100 hover:text-gray-700"
                }`}
              >
                {page}
              </button>
            </li>
          );
        })}

        {/* Next button */}
        <li>
          <button
            onClick={() =>
              currentPage < lastPage && handlePageClick(currentPage + 1)
            }
            disabled={currentPage === lastPage}
            className={`flex items-center justify-center px-3 h-10 leading-tight rounded-r-lg border ${
              currentPage === lastPage
                ? "text-gray-300 bg-gray-50 border-gray-200 cursor-not-allowed"
                : "text-gray-500 bg-white border-gray-300 hover:bg-gray-100 hover:text-gray-700"
            }`}
          >
            <span className="sr-only">Next</span>
            <ChevronRight className="w-5 h-5" />
          </button>
        </li>
      </ul>

      <div className="ml-4 text-sm text-gray-500 flex items-center">
        <span>
          Showing {(currentPage - 1) * perPage + 1}-
          {Math.min(currentPage * perPage, total)} of {total}
        </span>
      </div>
    </nav>
  );
}
