"use client";

import ReactPaginate from "react-paginate";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { PaginationConfig } from "../../../types/table.types";

interface TablePaginationProps {
  pagination?: PaginationConfig;
  className?: string;
}

const mergeClasses = (...classes: Array<string | undefined>) =>
  classes.filter(Boolean).join(" ");

export function TablePagination({
  pagination,
  className,
}: TablePaginationProps) {
  if (!pagination) return null;

  const { controller, totalItems, pageCount } = pagination;
  const { page, limit } = controller.params;

  const from = totalItems === 0 ? 0 : (page - 1) * limit + 1;
  const to = Math.min(page * limit, totalItems);

  return (
    <div
      className={mergeClasses(
        "mt-4 flex flex-col gap-4 sm:flex-row items-center sm:justify-between",
        className,
      )}
    >
      <p className="font-body text-sm text-text">
        Showing {from} to {to} of {totalItems} items
      </p>

      {pageCount > 1 && (
        <ReactPaginate
          forcePage={page - 1}
          pageCount={pageCount}
          onPageChange={({ selected }) => controller.set("page", selected + 1)}
          pageRangeDisplayed={5}
          marginPagesDisplayed={1}
          breakLabel="..."
          previousLabel={
            <ChevronLeft />
          }
          nextLabel={
              <ChevronRight />
          }
          containerClassName="flex items-center gap-3 cursor-pointer"
          pageClassName="list-none"
          pageLinkClassName="flex items-center justify-center font-body text-base font-medium text-heading transition-all hover:bg-gray-50"
          activeClassName="[&>a]:text-link-1"
          previousClassName="list-none"
          previousLinkClassName="flex items-center justify-center font-body text-base font-medium text-link-1 transition-all hover:bg-gray-50"
          nextClassName="list-none "
          nextLinkClassName="flex items-center justify-center font-body text-base font-medium text-link-1 transition-all hover:bg-gray-50"
          disabledClassName="pointer-events-none opacity-40"
          breakClassName="list-none"
          breakLinkClassName="flex items-center justify-center font-semibold text-link-1"
        />
      )}
    </div>
  );
}
