import React from "react";
import {Pagination} from 'react-bootstrap';

interface PaginationProps
{
    currentPage: number,
    totalRecords: number,
    recordLimit: number,
    sortOrder: string,
    sortColumn: number,
    handlePageChange: (item: number) => void
}

const TablePagination = ({totalRecords, currentPage, recordLimit, handlePageChange}: PaginationProps) => {
    const pageCount = totalRecords > 0 ? Math.ceil(totalRecords / recordLimit) : 0;

    // Calculate the starting and ending record index for the current page
    const startRecord = (currentPage - 1) * recordLimit + 1;
    const endRecord = Math.min(currentPage * recordLimit, totalRecords);

    const PaginationItems = () => {
        const paginationNumbers: (number | string)[] = [];
        const showMax = 5; // Max number of page numbers to show

        if (pageCount) {
            let startPage: number;
            let endPage: number;

            // Case 1: If total pages are less than or equal to the max pages to show, display all pages.
            if (pageCount <= showMax) {
                startPage = 1;
                endPage = pageCount;
            } else {
                // Case 2: If total pages are more than max pages to show, adjust start and end based on currentPage.
                if (currentPage <= Math.ceil(showMax / 2)) {
                    // Case 2a: If we're near the start, show the first `showMax` pages
                    startPage = 1;
                    endPage = showMax;
                } else {
                    if (currentPage + Math.floor(showMax / 2) >= pageCount) {
                        // Case 2b: If we're near the end, show the last `showMax` pages
                        startPage = pageCount - showMax + 1;
                        endPage = pageCount;
                    } else {
                        // Case 2c: Otherwise, show a centered page range around currentPage
                        startPage = currentPage - Math.floor(showMax / 2);
                        endPage = currentPage + Math.floor(showMax / 2);
                    }
                }
            }

            // Generate page numbers and include ellipsis
            let hasLeftEllipsis = false;
            let hasRightEllipsis = false;

            if (startPage > 1) {
                paginationNumbers.push(1); // Always show the first page
                hasLeftEllipsis = true;
            }

            for (let i = startPage; i <= endPage; i++) {
                paginationNumbers.push(i);
            }

            if (endPage < pageCount) {
                hasRightEllipsis = true;
                paginationNumbers.push(pageCount); // Always show the last page
            }

            // Add the ellipsis if necessary
            if (hasLeftEllipsis && paginationNumbers[1] !== 2) {
                paginationNumbers.splice(1, 0, '...'); // Add ellipsis after the first page
            }

            if (hasRightEllipsis && paginationNumbers[paginationNumbers.length - 2] !== pageCount - 1) {
                paginationNumbers.splice(paginationNumbers.length - 1, 0, '...'); // Add ellipsis before the last page
            }

            return (
                <>
                    {paginationNumbers.map((item, index) => (
                        typeof item == 'string' && item === '...' ? (
                            <Pagination.Item key={index} disabled>
                                {'...'}
                            </Pagination.Item>
                        ) : (
                            <Pagination.Item
                                active={currentPage === item}
                                key={index}
                                onClick={() => {
                                    // Only call handlePageChange if the item is a number (i.e., valid page number)
                                    if (typeof item === 'number' && currentPage !== item) {
                                        handlePageChange(item);
                                    }
                                }}
                                title={currentPage === item ? 'Active Page' : `Goto page ${item}`}
                            >
                                {item}
                            </Pagination.Item>
                        )
                    ))}
                </>
            );
        }

        return null; // If pageCount is not available, return nothing.
    };

    return (
        <div className="d-flex justify-content-center justify-content-sm-end flex-wrap align-items-center">
            {totalRecords > 0 ?
                <span className="me-1">Showing {startRecord} - {endRecord} of {totalRecords} records</span> : ""}

            {totalRecords && totalRecords > recordLimit ?
                <Pagination style={{float: "right", margin: 0}} data-bs-theme="light">
                    <Pagination.First disabled={currentPage === 1}
                                      onClick={() => {
                                          if (currentPage > 1) {
                                              handlePageChange(1)
                                          }
                                      }}
                    />
                    <Pagination.Prev disabled={currentPage === 1}
                                     onClick={() => {
                                         if (currentPage > 1) {
                                             handlePageChange(currentPage - 1);
                                         }
                                     }}
                    />
                    <PaginationItems/>
                    <Pagination.Next disabled={currentPage === pageCount}
                                     onClick={() => {
                                         if (currentPage < pageCount) {
                                             handlePageChange(currentPage + 1);
                                         }
                                     }}
                    />
                    <Pagination.Last disabled={currentPage === pageCount}
                                     onClick={() => {
                                         if (currentPage !== pageCount) {
                                             handlePageChange(pageCount);
                                         }
                                     }}
                    />
                </Pagination> : ""}
        </div>
    );
};

export default TablePagination;
