import React__default, { useState, useEffect } from 'react';
import { Checkbox } from '../../Field/checkbox/Checkbox.js';
import { CheckboxCell, Th, ThContainer } from '../styles.js';
import { getRowIdByIdentifier } from '../utils.js';

const TableHeader = ({ columns, selectAllRows, rows, selectedRows, rowIdentifier, 'data-testid': dataTestId, 'data-trackid': dataTrackId, }) => {
    const [selectAll, setSelectAll] = useState(false);
    useEffect(() => {
        if (selectedRows &&
            (selectedRows.length === 0 || selectedRows.length < rows.length)) {
            setSelectAll(false);
        }
    }, [selectedRows]);
    return (React__default.createElement("thead", { "data-testid": dataTestId, "data-trackid": dataTrackId },
        React__default.createElement("tr", { role: "row" },
            selectedRows && typeof selectAllRows === 'function' && (React__default.createElement(CheckboxCell, { as: "th", role: "columnheader" },
                React__default.createElement(Checkbox, { onChange: () => {
                        setSelectAll((prevSelectAllState) => {
                            const updatedSelectAll = !prevSelectAllState;
                            let rowIds = [];
                            if (rowIdentifier) {
                                rowIds = rows.map((row) => getRowIdByIdentifier(row, rowIdentifier));
                            }
                            selectAllRows(rowIds, updatedSelectAll);
                            return updatedSelectAll;
                        });
                    }, checked: selectAll, name: "select-all", value: 0, indeterminate: selectedRows.length > 0 && !selectAll }))),
            columns.map((column, index) => !column.hideHeader && (React__default.createElement(Th, { key: `${index}_${column.header.title}`, textAlign: column.textAlign, onClick: column.onClick, columnWidth: column.width, role: "columnheader" },
                React__default.createElement(ThContainer, null,
                    React__default.createElement("span", null, column.header.title),
                    column.header.icon)))))));
};

export { TableHeader as default };
