import ChevronRightIcon from '../../../../../../node_modules/@mui/icons-material/esm/ChevronRight.mjs';
import React__default, { useState, useEffect } from 'react';
import { useUniqueId } from '../../../utils/uniqueId.mjs';
import { mergeSx } from '../utils/mergeSx.mjs';
import { validateRowKey, getTableCellValue } from '../utils/tableUtils.mjs';
import { TABLE_ACTIONS_HEADER } from './TableActions.mjs';
import TableContainer from '../../../../../../node_modules/@mui/material/TableContainer/TableContainer.mjs';
import TableHead from '../../../../../../node_modules/@mui/material/TableHead/TableHead.mjs';
import TableRow$1 from '../../../../../../node_modules/@mui/material/TableRow/TableRow.mjs';
import TableBody from '../../../../../../node_modules/@mui/material/TableBody/TableBody.mjs';
import styled from '../../../../../../node_modules/@mui/material/styles/styled.mjs';
import Table from '../../../../../../node_modules/@mui/material/Table/Table.mjs';
import TableCell$1 from '../../../../../../node_modules/@mui/material/TableCell/TableCell.mjs';
import IconButton from '../../../../../../node_modules/@mui/material/IconButton/IconButton.mjs';
import Collapse from '../../../../../../node_modules/@mui/material/Collapse/Collapse.mjs';

const TABLE_CONTAINER_ID = 'table-container';
const EXPANDED_CONTENT_CLASSNAME = 'expanded-content';
// Keep the expanded content left aligned while the table is scrolled horizontally.
// We want to be able to scroll the table horizontally while making it appear like the expanded content is
// is not scrolling. To do this, we need to adjust the margin-left of the expanded content to match the
// scrollLeft of the table container.
const leftAlignExpandedContent = (containerId)=>{
    const container = document.getElementById(containerId);
    const expandedContentDivs = document.querySelectorAll(`#${containerId} .${EXPANDED_CONTENT_CLASSNAME}`);
    expandedContentDivs.forEach((expandedContent)=>{
        expandedContent.style.marginLeft = container?.scrollLeft + 'px';
    });
};
const StyledTable = styled(Table)(({ hasActions, hasExpandedContent, theme })=>[
        hasActions && {
            // For some reason with position sticky, the table is 2px wider than the container
            width: 'calc(100% - 2px)'
        },
        hasExpandedContent && {
            // Remove spacing between expand more icon and first column
            '& tr td:nth-of-type(2), & tr th:nth-of-type(2)': {
                paddingLeft: theme.spacing(0)
            }
        }
    ]);
const StyledTableRow = styled(TableRow$1)(({ clickable })=>[
        {
            width: 'fit-content'
        },
        clickable && {
            cursor: 'pointer'
        }
    ]);
const StyledTableCell = styled(TableCell$1)(({ theme, isTableActionsCell })=>[
        {
            padding: theme.spacing(0.5, 1),
            minWidth: 80,
            whiteSpace: 'nowrap'
        },
        isTableActionsCell && {
            position: 'sticky',
            right: 0,
            width: '1%'
        }
    ]);
const TableCell = ({ children, className, TypographyComponent: Typography, ...props })=>{
    const value = getTableCellValue(children);
    return /*#__PURE__*/ React__default.createElement(StyledTableCell, {
        className: className,
        ...props
    }, typeof value === 'string' ? /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body2"
    }, value) : children);
};
const ExpandMoreCell = styled(TableCell$1)(({ theme, hasExpandedContent })=>[
        {
            padding: theme.spacing(1),
            minWidth: 'unset'
        },
        hasExpandedContent && {
            borderBottom: 'none'
        }
    ]);
const ExpandedContentCell = styled(TableCell)({
    padding: 0
});
const ExpandedContentContainer = styled('div')(({ width, theme })=>({
        padding: theme.spacing(0.5, 2, 1),
        width
    }));
const ChevronIcon = styled(ChevronRightIcon)(({ open })=>({
        transform: open ? 'rotate(90deg)' : 'rotate(0deg)'
    }));
const TableHeaderCell = styled(TableCell$1)(({ isActionsHeader, isExpandedContentHeader, width, theme })=>[
        {
            padding: theme.spacing(1.25, 1),
            width,
            minWidth: width
        },
        isActionsHeader && {
            minWidth: 80,
            position: 'sticky',
            right: 0,
            width: width ?? '1%'
        },
        isExpandedContentHeader && {
            padding: theme.spacing(0, 0, 0, 1),
            width: theme.spacing(4.5),
            minWidth: 'unset'
        }
    ]);
const TableRow = ({ id, ExpandedContent, item, itemRenderer, onRowClick, tableWidth, tableContainerId, getItemActionProps, TableActionsComponent: TableActions, TypographyComponent: Typography, isOpen: isOpenProp, onOpenChange, tableCellSx, tableActionsCellSx, tableRowSx, expandMoreCellSx, expandedContentContainerSx })=>{
    const isOpenControlled = isOpenProp !== undefined;
    const [openState, setOpenState] = useState(false);
    const open = isOpenControlled ? isOpenProp : openState;
    useEffect(()=>{
        if (open) {
            leftAlignExpandedContent(tableContainerId);
        }
    }, [
        open,
        tableContainerId
    ]);
    const toggleOpen = (e)=>{
        e.stopPropagation();
        if (isOpenControlled) {
            onOpenChange?.({
                id,
                open: !open
            });
        } else {
            setOpenState((prev)=>!prev);
        }
    };
    const handleRowClick = (e)=>{
        if (onRowClick) {
            onRowClick(id);
        } else if (ExpandedContent) {
            toggleOpen(e);
        }
    };
    const stopEventPropagation = (e)=>onRowClick ? e.stopPropagation() : null;
    return /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, /*#__PURE__*/ React__default.createElement(StyledTableRow, {
        clickable: !!onRowClick,
        expanded: open,
        onClick: handleRowClick,
        sx: tableRowSx
    }, ExpandedContent && /*#__PURE__*/ React__default.createElement(ExpandMoreCell, {
        hasExpandedContent: !!ExpandedContent,
        sx: mergeSx(tableCellSx, expandMoreCellSx)
    }, /*#__PURE__*/ React__default.createElement(IconButton, {
        "aria-label": "expand row",
        onClick: toggleOpen,
        size: "small"
    }, ExpandedContent && /*#__PURE__*/ React__default.createElement(ChevronIcon, {
        open: open
    }))), itemRenderer.map((column)=>/*#__PURE__*/ React__default.createElement(ExpandMoreCell, {
            sx: tableCellSx,
            hasExpandedContent: !!ExpandedContent,
            key: `row-${id}-col-${String(column.title)}`
        }, column.getValue(item))), getItemActionProps && /*#__PURE__*/ React__default.createElement(StyledTableCell, {
        isTableActionsCell: true,
        onClick: stopEventPropagation,
        sx: mergeSx(tableCellSx, tableActionsCellSx)
    }, /*#__PURE__*/ React__default.createElement(TableActions, getItemActionProps(item)))), ExpandedContent && /*#__PURE__*/ React__default.createElement(TableRow$1, null, /*#__PURE__*/ React__default.createElement(ExpandedContentCell, {
        TypographyComponent: Typography,
        colSpan: itemRenderer.length + 1
    }, /*#__PURE__*/ React__default.createElement(Collapse, {
        in: open,
        timeout: "auto",
        unmountOnExit: true
    }, /*#__PURE__*/ React__default.createElement(ExpandedContentContainer, {
        className: EXPANDED_CONTENT_CLASSNAME,
        width: tableWidth,
        sx: expandedContentContainerSx
    }, /*#__PURE__*/ React__default.createElement(ExpandedContent, {
        data: item
    }))))));
};
const TableCore = ({ ExpandedContent, itemRenderer, items, rowKeyExtractor, onRowClick, getItemActionProps, TableActionsComponent: TableActions, TypographyComponent: Typography, disableBottomBorder, titleVariant = 'body2', onOpenChange, openIds, tableCellSx, tableActionsCellSx, tableRowSx, expandMoreCellSx, expandedContentContainerSx })=>{
    const containerId = useUniqueId(TABLE_CONTAINER_ID);
    const [, setTableWidth] = useState();
    // This useEffect is used to keep the expanded content left aligned while the table is scrolled horizontally.
    useEffect(()=>{
        const container = document.getElementById(containerId);
        const originalTableWidth = document.querySelector(`#${containerId} thead`)?.getBoundingClientRect().width;
        // On scroll, adjust the position of the expanded content to keep it in view.
        function handleScroll() {
            if (!originalTableWidth || !container) return;
            const tableWidth = container.getBoundingClientRect().width;
            // If the table is scrolled all the way to the right, then we no longer need to adjust.
            if (originalTableWidth - container.scrollLeft + 16 >= tableWidth) {
                leftAlignExpandedContent(containerId);
            }
        }
        // on window resize, get the table width so we can set the width of the expanded content.
        function handleResize() {
            setTableWidth(container?.getBoundingClientRect().width ?? 0);
            handleScroll();
        }
        handleResize();
        window.addEventListener('resize', handleResize);
        container?.addEventListener('scroll', handleScroll);
        return ()=>{
            container?.removeEventListener('scroll', handleScroll);
            window.removeEventListener('resize', handleResize);
        };
    }, [
        containerId
    ]);
    validateRowKey(items, rowKeyExtractor);
    return /*#__PURE__*/ React__default.createElement(TableContainer, {
        id: containerId
    }, /*#__PURE__*/ React__default.createElement(StyledTable, {
        hasActions: !!getItemActionProps,
        hasExpandedContent: !!ExpandedContent
    }, /*#__PURE__*/ React__default.createElement(TableHead, null, /*#__PURE__*/ React__default.createElement(TableRow$1, null, ExpandedContent && /*#__PURE__*/ React__default.createElement(TableHeaderCell, {
        isExpandedContentHeader: true,
        sx: expandMoreCellSx
    }, /*#__PURE__*/ React__default.createElement(React__default.Fragment, null)), itemRenderer.map((column)=>{
        const renderTitle = column.renderTitle ?? (()=>column.title);
        const width = column.width;
        return /*#__PURE__*/ React__default.createElement(TableHeaderCell, {
            key: `col-header-${String(column.title)}`,
            width: width
        }, /*#__PURE__*/ React__default.createElement(Typography, {
            variant: titleVariant,
            color: titleVariant === 'h4' ? 'primary' : 'secondary'
        }, renderTitle()));
    }), getItemActionProps && /*#__PURE__*/ React__default.createElement(TableHeaderCell, {
        isActionsHeader: true,
        sx: mergeSx(tableCellSx, tableActionsCellSx)
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: titleVariant,
        color: titleVariant === 'h4' ? 'primary' : 'secondary'
    }, TABLE_ACTIONS_HEADER)))), /*#__PURE__*/ React__default.createElement(TableBody, null, items.map((item)=>{
        const id = rowKeyExtractor ? rowKeyExtractor(item) : item.id;
        const isOpen = openIds?.has(id);
        return /*#__PURE__*/ React__default.createElement(TableRow, {
            ExpandedContent: ExpandedContent,
            TableActionsComponent: TableActions,
            TypographyComponent: Typography,
            getItemActionProps: getItemActionProps,
            id: id,
            item: item,
            itemRenderer: itemRenderer,
            key: id,
            onRowClick: onRowClick,
            tableContainerId: containerId,
            disableBottomBorder: disableBottomBorder,
            isOpen: isOpen,
            onOpenChange: onOpenChange,
            tableCellSx: tableCellSx,
            tableActionsCellSx: tableActionsCellSx,
            tableRowSx: tableRowSx,
            expandMoreCellSx: expandMoreCellSx,
            expandedContentContainerSx: expandedContentContainerSx
        });
    }))));
};

export { TableCore };
//# sourceMappingURL=Table.mjs.map
