import { useState } from 'react';

// Types
interface PaginationState {
    currentPage: number;
    pageSize: number;
    sortColumn?: string;
    sortDirection?: 'ASC' | 'DESC';
}

interface StatsState {
    totalRows: number;
    totalPages: number;
}

export const usePagination = () => {
    const initialPaginationState: PaginationState = {
        currentPage: 1,
        pageSize: 100,
        sortColumn: undefined,
        sortDirection: undefined,
    };

    const initialStatsState: StatsState = {
        totalRows: 0,
        totalPages: 1,
    };

    const [pagination, setPagination] = useState<PaginationState>(initialPaginationState);
    const [stats, setStats] = useState<StatsState>(initialStatsState);

    const handlePageSizeChange = (val: string) => {
        const newPageSize = parseInt(val) || 10;
        setPagination((prev) => ({ ...prev, pageSize: newPageSize }));
    };

    const handlePageChange = (val: string) => {
        const newPage = parseInt(val) || 1;
        if (newPage >= 1 && newPage <= stats.totalPages) {
            setPagination((prev) => ({ ...prev, currentPage: newPage }));
        }
    };

    const handlePreviousPage = () => {
        setPagination((prev) =>
            prev.currentPage > 1
                ? { ...prev, currentPage: prev.currentPage - 1 }
                : prev
        );
    };

    const handleNextPage = () => {
        setPagination((prev) =>
            prev.currentPage < stats.totalPages
                ? { ...prev, currentPage: prev.currentPage + 1 }
                : prev
        );
    };

    const resetPagination = () => {
        setPagination(initialPaginationState);
        setStats(initialStatsState);
    };

    return {
        pagination,
        stats,
        setPagination,
        setStats,
        handlePageSizeChange,
        handlePageChange,
        handlePreviousPage,
        handleNextPage,
        resetPagination,
    };
};