"use client"

import { Button } from "@/Components/UI/Button"
import { router } from "@inertiajs/react"

export default function Pagination({
  links,
  currentPage,
  lastPage,
  preserveState = true,
  preserveScroll = true,
  only = [],
  className = "",
}) {
  if (!links || lastPage <= 1) {
    return null;
  }

  const handlePageChange = (url) => {
    if (!url) return;

    router.get(
      url,
      {},
      {
        preserveState,
        preserveScroll,
        only,
      },
    );
  };

  
  const pageLinks = links.filter(
    (link) =>
      link.label !== "&laquo; Previous" &&
      link.label !== "Next &raquo;" &&
      !link.label.includes("Previous") &&
      !link.label.includes("Next"),
  );

  const previousLink = links.find((link) => link.label === "&laquo; Previous" || link.label.includes("Previous"));
  const nextLink = links.find((link) => link.label === "Next &raquo;" || link.label.includes("Next"));

  return (
    <div className={`flex items-center justify-center gap-2 ${className}`}>
      {/* Previous Button */}
      <Button
        variant="ghost"
        size="sm"
        className={`${previousLink?.url ? "text-gray-600 hover:text-gray-800" : "text-gray-400 cursor-not-allowed"}`}
        onClick={() => handlePageChange(previousLink?.url)}
        disabled={!previousLink?.url}
      >
        &lt;
      </Button>

      {/* Page Numbers */}
      {pageLinks.map((link, index) => {
        // Handle ellipsis
        if (link.label === "...") {
          return (
            <span key={`ellipsis-${index}`} className="text-gray-400 mx-1">
              ...
            </span>
          );
        }

        const isActive = link.active;
        const pageNumber = link.label;

        return (
          <Button
            key={`page-${pageNumber}-${index}`}
            size="sm"
            variant={isActive ? "default" : "ghost"}
            className={
              isActive
                ? "bg-gradient-to-r from-primary to-secondary text-white hover:from-sky-600 hover:to-cyan-600"
                : "text-gray-600 hover:text-gray-800 hover:bg-gray-100"
            }
            onClick={() => handlePageChange(link.url)}
            disabled={!link.url}
          >
            {pageNumber}
          </Button>
        );
      })}

      {/* Next Button */}
      <Button
        variant="ghost"
        size="sm"
        className={`${nextLink?.url ? "text-gray-600 hover:text-gray-800" : "text-gray-400 cursor-not-allowed"}`}
        onClick={() => handlePageChange(nextLink?.url)}
        disabled={!nextLink?.url}
      >
        &gt;
      </Button>
    </div>
  );
}