import { useMemo, useCallback } from 'react';
import { getRowId } from '../Table.utils.js';

function useTableSelection({ data, rowKey, selectionType = 'checkbox', selectedRows = [], onSelectionChange, }) {
    const isAllSelected = useMemo(() => selectedRows.length === data.length && data.length > 0, [selectedRows.length, data.length]);
    const isIndeterminate = useMemo(() => selectedRows.length > 0 && selectedRows.length < data.length, [selectedRows.length, data.length]);
    const handleSelectAll = useCallback((checked) => {
        if (!onSelectionChange || selectionType !== 'checkbox')
            return;
        if (checked) {
            const allRowIds = data.map((row, index) => getRowId(row, index, rowKey));
            onSelectionChange(allRowIds);
        }
        else {
            onSelectionChange([]);
        }
    }, [data, rowKey, selectionType, onSelectionChange]);
    const handleSelectionChange = useCallback((rowId, selected) => {
        if (!onSelectionChange)
            return;
        const newSelectedRows = selectionType === 'checkbox'
            ? selected
                ? [...selectedRows, rowId]
                : selectedRows.filter(id => id !== rowId)
            : selected ? [rowId] : [];
        onSelectionChange(newSelectedRows);
    }, [selectionType, selectedRows, onSelectionChange]);
    const handleClearSelection = useCallback(() => {
        onSelectionChange === null || onSelectionChange === void 0 ? void 0 : onSelectionChange([]);
    }, [onSelectionChange]);
    return {
        isAllSelected,
        isIndeterminate,
        handleSelectAll,
        handleSelectionChange,
        handleClearSelection,
    };
}

export { useTableSelection };
