'use client';

// @/app/component/pagination.tsx
import React from 'react';
import Styles from '../styles/common.module.scss';

interface PaginationProps {
	total: number;
    page?: number;
	perPage?: number;
    onChange: (page: number) => void;
}

export default function Pagination({ total, page = 1, perPage = 10, onChange }: PaginationProps) {
	const totalPage = (Math.ceil(total / perPage));

    const handlePrevious = () => {
        if (page > 1) {
            onChange(page - 1);
        }
    };

    const handleNext = () => {
        if (page < totalPage) {
            onChange(page + 1);
        }
    };

	if (page > totalPage) {
		return;
	}

    return (
        <div id={Styles.pagination} className='mt-3'>
			{totalPage > 1 && (
				<button type='button' onClick={handlePrevious} disabled={page === 1}>
					이전
				</button>
			)}

			{totalPage > 7 ? (
				<>
					{page > 3 && <button onClick={() => onChange(1)}>1</button>}
					{page > 4 && <span>...</span>}

					{Array.from({ length: 5 }, (_, index) => {
						const pageNumber = page - 2 + index;
						if (pageNumber > 0 && pageNumber <= totalPage) {
							return (
								<button type='button'
									key={pageNumber}
									onClick={() => onChange(pageNumber)}
									{...(page === pageNumber ? { className: Styles.active } : {})}
								>
									{pageNumber}
								</button>
							);
						}
						return null;
					})}

					{page < totalPage - 3 && <span>...</span>}
					{page < totalPage - 2 && <button type='button' onClick={() => onChange(totalPage)}>{totalPage}</button>}
				</>
			) : (
				Array.from({ length: totalPage }, (_, index) => (
					<button type='button'
						key={index + 1}
						onClick={() => onChange(index + 1)}
						{...(page === index + 1 ? { className: Styles.active } : {})}
					>
						{index + 1}
					</button>
				))
			)}

			{totalPage > 1 && (
				<button type='button' onClick={handleNext} disabled={page === totalPage}>
					다음
				</button>
			)}
        </div>
    );
}