var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React, { forwardRef } from "react";
import { ChevronDownUpIcon, ChevronUpDownIcon, MinusIcon, PlusIcon, } from "@navikt/aksel-icons";
import { Button } from "../../../button/index.js";
import { useDataGridContext } from "../../../data-grid/root/DataGridRoot.context.js";
import { CheckboxInput } from "../../../form/checkbox/checkbox-input/CheckboxInput.js";
import { RadioInput } from "../../../form/radio/radio-input/RadioInput.js";
import { Skeleton } from "../../../skeleton/index.js";
import { Label } from "../../../typography/index.js";
import { useId } from "../../../utils-external/index.js";
import { cl, composeEventHandlers } from "../../../utils/helpers/index.js";
import { consoleWarning } from "../../../utils/helpers/consoleWarning.js";
import { DataTableBaseCell } from "../base-cell/DataTableBaseCell.js";
import { DataTableColumnHeader } from "../column-header/DataTableColumnHeader.js";
import { getDataTableDetailsPanelId, useDataTableDetailsPanel, } from "../hooks/useTableDetailsPanel.js";
import { useDataTableContext, useDataTableLocation, } from "../root/DataTableRoot.context.js";
import { DataTableTd } from "../td/DataTableTd.js";
const ACTION_CELL_WIDTH = 50;
const ACTION_CELL_CSS_WIDTH = `${ACTION_CELL_WIDTH}px`;
const DataTableTr = forwardRef((_a, forwardedRef) => {
    var _b;
    var { className, children, selected: selectedProp = false, rowId, onClick } = _a, rest = __rest(_a, ["className", "children", "selected", "rowId", "onClick"]);
    const { layout, selectionState, onRowAction, tableItems } = useDataTableContext();
    const { location } = useDataTableLocation();
    const renderFillerCell = layout === "fixed" && children;
    const selected = (_b = selectionState.selection.isRowSelected(rowId !== null && rowId !== void 0 ? rowId : "")) !== null && _b !== void 0 ? _b : selectedProp;
    const handleClick = location === "tbody" &&
        rowId !== undefined &&
        ((selectionState.selectionTrigger === "row" &&
            selectionState.selection.mode !== "none") ||
            onRowAction)
        ? (event) => {
            var _a, _b, _c;
            if (rowId === undefined ||
                isInteractiveTarget(event.target) ||
                ((_a = event.target) === null || _a === void 0 ? void 0 : _a.closest("[data-prevent-row-click]"))) {
                return;
            }
            if (onRowAction) {
                const rowData = (_b = tableItems.itemDetails.get(rowId)) === null || _b === void 0 ? void 0 : _b.rowData;
                if (rowData) {
                    onRowAction({
                        row: rowData,
                        id: rowId,
                        event,
                    });
                }
                else {
                    consoleWarning(`DataGrid.Table: Unable to find row data for rowId ${rowId} when calling onRowAction.`);
                }
            }
            if (event.defaultPrevented) {
                return;
            }
            const selection = window.getSelection();
            if (selection && selection.toString().length > 0) {
                return;
            }
            if (selectionState.selectionTrigger === "row" &&
                selectionState.selection.mode !== "none") {
                const rowData = (_c = tableItems.itemDetails.get(rowId)) === null || _c === void 0 ? void 0 : _c.rowData;
                if (!rowData) {
                    consoleWarning(`DataGrid.Table: No row data found for rowId ${rowId}. This may cause issues with selection if enableRowSelection is used.`);
                }
                selectionState.selection.toggleSelection(rowId, rowData);
            }
        }
        : undefined;
    return (React.createElement("tr", Object.assign({}, rest, { 
        // Avoid setting onClick if not needed, since this causes NVDA to announce the row as clickable.
        onClick: (onClick || handleClick) && composeEventHandlers(onClick, handleClick), ref: forwardedRef, className: cl("aksel-data-table__tr", className), "data-selected": selected }),
        React.createElement(RowExpansionCell, { rowId: rowId }),
        React.createElement(RowSelectionCell, { rowId: rowId }),
        children,
        renderFillerCell && (React.createElement("td", { "aria-hidden": true, className: "aksel-data-table__cell aksel-data-table__filler-cell", "data-block-keyboard-nav": true }))));
});
function RowExpansionCell({ rowId }) {
    const { isLoading } = useDataGridContext();
    const { tableId, loading, stickyStart } = useDataTableContext();
    const stickyExpansion = stickyStart.expansion;
    const expansionHeaderId = useId();
    const { location } = useDataTableLocation();
    const { isExpanded, isDetailsPanelExpandable, toggleExpansion, enableDetailsPanel, isAllExpanded, toggleAll, showExpandAll, } = useDataTableDetailsPanel();
    if (!enableDetailsPanel) {
        return null;
    }
    if (isLoading && (loading === null || loading === void 0 ? void 0 : loading.variant) === "skeleton") {
        if (location === "thead") {
            return (React.createElement(DataTableColumnHeader, { id: expansionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", "data-block-keyboard-nav": true, label: "", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined }));
        }
        return (React.createElement(DataTableBaseCell, { as: "td", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined },
            React.createElement(Skeleton, { variant: "text" })));
    }
    if (location === "thead" && !showExpandAll) {
        return (React.createElement(DataTableColumnHeader, { id: expansionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", "data-block-keyboard-nav": true, label: "", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined }));
    }
    if (location === "thead") {
        return (React.createElement(DataTableColumnHeader, { id: expansionHeaderId, align: "center", width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined },
            React.createElement(Button, { variant: "tertiary", "data-color": "neutral", size: "xsmall", onClick: toggleAll, "aria-expanded": isAllExpanded, "aria-label": isAllExpanded ? "Skjul alle rader" : "Vis alle rader", icon: isAllExpanded ? (React.createElement(ChevronDownUpIcon, { "aria-hidden": true })) : (React.createElement(ChevronUpDownIcon, { "aria-hidden": true })) })));
    }
    if (!rowId) {
        return null;
    }
    const isRowExpanded = isExpanded(rowId);
    const canExpandRow = isDetailsPanelExpandable(rowId);
    const expansionId = getDataTableDetailsPanelId(tableId, rowId);
    if (!canExpandRow) {
        return (React.createElement(DataTableTd, { cellType: "action", preventRowClick: true, isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined }));
    }
    return (React.createElement(DataTableTd, { cellType: "action", preventRowClick: true, isSticky: stickyExpansion && "start", style: stickyExpansion ? { left: 0 } : undefined },
        React.createElement(Button, { variant: "tertiary", "data-color": "neutral", size: "xsmall", onClick: (e) => {
                e.stopPropagation();
                toggleExpansion(rowId);
            }, "aria-expanded": isRowExpanded, "aria-controls": expansionId, "aria-label": isRowExpanded ? "Skjul detaljer" : "Vis detaljer", icon: isRowExpanded ? React.createElement(MinusIcon, { "aria-hidden": true }) : React.createElement(PlusIcon, { "aria-hidden": true }) })));
}
/**
 * TODO: How do these cells handle multiple thead rows, or col/row-spans?
 * TODO: a11y for labels
 */
function RowSelectionCell({ rowId }) {
    var _a, _b;
    const { isLoading } = useDataGridContext();
    const { selectionState, stickyStart, loading } = useDataTableContext();
    const stickySelection = stickyStart.selection;
    const stickySelectionOffset = stickyStart.selectionOffset;
    const { location } = useDataTableLocation();
    const { tableItems } = useDataTableContext();
    const inputId = useId();
    const selectionHeaderId = useId();
    const { selection, renderSelection } = selectionState;
    if (selection.mode === "none" || !renderSelection) {
        return null;
    }
    if (isLoading && (loading === null || loading === void 0 ? void 0 : loading.variant) === "skeleton") {
        if (location === "thead") {
            return (React.createElement(DataTableColumnHeader, { id: selectionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", "data-block-keyboard-nav": true, isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined }));
        }
        return (React.createElement(DataTableBaseCell, { as: "td", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            React.createElement(Skeleton, { variant: "text" })));
    }
    /* TODO: A11y support */
    if (selection.mode === "multiple" && location === "thead") {
        const theadCheckboxProps = selection.getTheadCheckboxProps();
        let labelText = "Velg alle synlige rader";
        if (theadCheckboxProps.checked) {
            labelText = "Fjern alle synlige valgte rader";
        }
        return (React.createElement(DataTableColumnHeader, { id: selectionHeaderId, align: "center", width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            React.createElement(Label, { htmlFor: inputId, visuallyHidden: true }, labelText),
            React.createElement(CheckboxInput, Object.assign({}, theadCheckboxProps, { id: inputId, compact: true }))));
    }
    if (selection.mode === "single" && location === "thead") {
        return (React.createElement(DataTableColumnHeader, { id: selectionHeaderId, width: { value: ACTION_CELL_CSS_WIDTH }, cellType: "action", label: "", "data-block-keyboard-nav": true, isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined }));
    }
    if (rowId == null) {
        return null;
    }
    if (selection.mode === "multiple" && location === "tbody") {
        return (React.createElement(DataTableTd, { cellType: "action", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            React.createElement(CheckboxInput, Object.assign({}, selection.getRowCheckboxProps(rowId, (_a = tableItems.itemDetails.get(rowId)) === null || _a === void 0 ? void 0 : _a.rowData), { compact: true }))));
    }
    if (selection.mode === "single" && location === "tbody") {
        return (React.createElement(DataTableTd, { cellType: "action", isSticky: stickySelection && "start", style: stickySelection ? { left: stickySelectionOffset } : undefined },
            React.createElement(RadioInput, Object.assign({}, selection.getRowRadioProps(rowId, (_b = tableItems.itemDetails.get(rowId)) === null || _b === void 0 ? void 0 : _b.rowData)))));
    }
    return null;
}
/* Utils */
function isInteractiveTarget(target) {
    return !!(target === null || target === void 0 ? void 0 : target.closest("a, button, input, select, textarea"));
}
export { DataTableTr, ACTION_CELL_WIDTH };
//# sourceMappingURL=DataTableTr.js.map