import { useCallback, useMemo } from 'react';
import { isGroupColumns } from '../../../utils';
import { getGridPositions } from './utils';
export const useLogic = ({ columns, onSort, sorting, uncheckedRowsCount, rowsCount, onSelectAllRows, }) => {
    const isChecked = useMemo(() => !uncheckedRowsCount && rowsCount > 0, [uncheckedRowsCount, rowsCount]);
    const isIndeterminate = useMemo(() => uncheckedRowsCount > 0 && uncheckedRowsCount < rowsCount, [uncheckedRowsCount, rowsCount]);
    const isDisabled = !rowsCount;
    const checkboxProps = useMemo(() => ({
        checked: isChecked,
        disabled: isDisabled,
        indeterminate: isIndeterminate,
        onChange: onSelectAllRows,
    }), [isChecked, isDisabled, isIndeterminate, onSelectAllRows]);
    const handleSort = useCallback((field) => {
        if (!onSort) {
            return;
        }
        const isCurrentField = sorting?.fieldId === field;
        if (isCurrentField && sorting?.sort === 'asc') {
            return onSort({ fieldId: field, sort: 'desc' });
        }
        if (isCurrentField && sorting?.sort === 'desc') {
            return onSort(undefined);
        }
        onSort({ fieldId: field, sort: 'asc' });
    }, [sorting, onSort]);
    const gridPositions = useMemo(() => {
        return getGridPositions(columns);
    }, [columns]);
    const headerCssVars = useCallback((position) => {
        if (!position) {
            return {};
        }
        return {
            '--grid-column-start': position.start,
            '--grid-column-end': position.end,
        };
    }, []);
    return {
        checkboxProps,
        handleSort,
        gridPositions,
        headerCssVars,
        hasGroupedColumns: columns.some(isGroupColumns),
    };
};
