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

export function useSortedPaginatedRecords<T>(data: T[] = [], defaultSort: DataTableSortStatus) {
    // ✅ Sort status pakai useState biasa (tidak sync ke URL)
    const [sortStatus, setSortStatus] = useState<DataTableSortStatus>(defaultSort);

    // ✅ Pagination pakai URL
    const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1));
    const [pageSize, setPageSize] = useQueryState('pageSize', parseAsInteger.withDefault(10));

    const [records, setRecords] = useState<T[]>([]);

    useEffect(() => {
        const sorted = sortBy(data, sortStatus.columnAccessor);
        setRecords(sortStatus.direction === 'desc' ? sorted.reverse() : sorted);
        setPage(1); // reset ke page 1 kalau sort berubah
    }, [data, sortStatus, setPage]);

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

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