import { useEffect, useState } from 'react';
import { DataTableSortStatus } from 'mantine-datatable';
import { sortBy } from 'lodash';

export function useSortedPaginatedRecords<T>(data: T[] = [], defaultSort: DataTableSortStatus) {
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus>(defaultSort);
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [records, setRecords] = useState<T[]>([]);

    useEffect(() => {
        const sorted = sortBy(data, sortStatus.columnAccessor);
        setRecords(sortStatus.direction === 'desc' ? sorted.reverse() : sorted);
        setPage(1);
    }, [data, sortStatus]);

    const paginatedRecords = records.slice((page - 1) * pageSize, page * pageSize);

    return {
        sortStatus,
        setSortStatus,
        page,
        setPage,
        pageSize,
        setPageSize,
        paginatedRecords,
        totalRecords: data.length,
    };
}
