import { jsx, jsxs } from 'react/jsx-runtime';
import React__default, { useState, useCallback, useMemo, useEffect, useImperativeHandle } from 'react';
import classNames from '../../_virtual/index.js';
import StepInnerTable from './Components/StepInnerTable.js';
import { getUpdatedSelectedRows, getUpdatedPartialSelect, getUpdatedExpandedRows, hasSelectedIds, gettingBlockMap, updateCheckboxStatus } from './Components/handleStepCheckBox.js';
import StepsTitle from './Components/StepsTitle.js';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty.js';
import Typography from '../Typography/Typography.js';

const ACCORDION_TITLE_ROW_HEIGHT = 32;
const TABLE_HEADER_ROW_HEIGHT = 32;
const StepLandingTable = React__default.memo(React__default.forwardRef(({ tableMeta = [], tableData = [], noDataContent, height = '100%', withFixedHeader = false, headerType, handleDragStart, onDragEnd, editMode, editComponent, NlpComponent, AddNlp, handleAccordion, handleViewComponent, onSelectClick, loading = false, isViewPrivilegeMode = false, defaultExpanded = 'Steps', isHeaderRequired = true, isClientSide = false, highlightKey, onHighlightComplete, isDraggable = true, isMaximize = false, }, ref) => {
    const [ViewComponent, setViewComponent] = useState(null);
    const [viewModeId, setViewModeId] = useState(null);
    const [expandedRows, setExpandedRows] = useState({});
    const [expandStepGroup, setExpandStepGroup] = useState(new Map());
    const [isBulkEnable, setBulkEnable] = useState(false);
    const onAccordionClick = useCallback((title, action) => {
        const row = tableData.find((row) => row.title === title);
        if (!row || !row.data || row.data.length === 0) {
            return;
        }
        setExpandedRows((prev) => ({
            ...prev,
            [title]: action === 'open' ? true : !prev[title],
        }));
    }, [tableData]);
    const isExpanded = useMemo(() => (title) => expandedRows[title] ?? false, [expandedRows]);
    const toggleViewRow = useCallback((row) => {
        setViewModeId((prev) => (prev === row?.stepId ? null : row?.stepId));
    }, []);
    const handleClick = useCallback((item) => {
        toggleViewRow(item);
        const Component = handleViewComponent?.(item, toggleViewRow);
        if (Component) {
            setViewComponent(() => Component);
        }
        else {
            toggleViewRow(null);
        }
    }, [handleViewComponent, toggleViewRow]);
    const [selectedRows, setSelectedRows] = useState(Object.fromEntries(tableData.map((section) => [section.title, new Set()])));
    const [stepPartialSelect, setStepPartialSelect] = useState(new Set());
    useEffect(() => {
        setSelectedRows((pre) => getUpdatedSelectedRows(tableData, pre));
        setStepPartialSelect((prevPartialSelect) => getUpdatedPartialSelect(tableData, prevPartialSelect));
        setExpandedRows((prev) => getUpdatedExpandedRows(tableData, prev, defaultExpanded));
        if (selectedRows && !hasSelectedIds(selectedRows))
            return;
        const { updateSelectRow, updateStepPartialSelect } = gettingBlockMap(tableData, selectedRows, stepPartialSelect);
        if (updateStepPartialSelect)
            setStepPartialSelect(updateStepPartialSelect);
        if (updateSelectRow)
            setSelectedRows(updateSelectRow);
    }, [tableData]);
    useEffect(() => {
        if (hasSelectedIds(selectedRows)) {
            const updatedSelection = {
                ...selectedRows,
                partialSelected: stepPartialSelect,
            };
            onSelectClick?.(updatedSelection);
        }
        else {
            onSelectClick?.(selectedRows);
        }
    }, [selectedRows]);
    const handleMainCheckbox = useCallback((sectionTitle, checked) => {
        const allRowIds = tableData
            .find((section) => section.title === sectionTitle)
            ?.data.map((row) => row.stepId);
        if (allRowIds) {
            setSelectedRows((prev) => ({
                ...prev,
                [sectionTitle]: checked ? new Set(allRowIds) : new Set(),
            }));
            if (!checked)
                setStepPartialSelect(new Set());
        }
    }, [tableData]);
    const handleUpdateCheckboxState = useCallback((tableData, rowData, isChecked, sectionTitle) => {
        const { updateSelectRow, updateStepPartialSelect } = updateCheckboxStatus(tableData, rowData, isChecked, selectedRows, stepPartialSelect, sectionTitle);
        if (updateStepPartialSelect)
            setStepPartialSelect(updateStepPartialSelect);
        if (updateSelectRow)
            setSelectedRows(updateSelectRow);
    }, [selectedRows, stepPartialSelect]);
    const handleRowCheckbox = useCallback((sectionTitle, row, isChecked) => {
        handleUpdateCheckboxState(tableData, row, isChecked, sectionTitle);
    }, [tableData, handleUpdateCheckboxState]);
    const isAllSelected = useCallback((sectionTitle, totalRows) => {
        const isSelected = totalRows > 0 && selectedRows[sectionTitle]?.size === totalRows;
        if (sectionTitle.includes('Script')) {
            setBulkEnable(isSelected);
        }
        return isSelected;
    }, [selectedRows]);
    const isPartialSelected = useCallback((sectionTitle, totalRows) => {
        const selectedCount = selectedRows[sectionTitle]?.size || 0;
        return selectedCount > 0 && selectedCount < totalRows;
    }, [selectedRows]);
    const isStepGroupExpanded = useCallback((stepId) => expandStepGroup.has(stepId), [expandStepGroup]);
    const getScrollableRowLimit = useCallback((title) => title === 'Steps' && !isViewPrivilegeMode ? 12 : 15, [isViewPrivilegeMode]);
    const isScrollableSection = useCallback((rows) => height !== 'auto' &&
        (rows?.data?.length ?? 0) > getScrollableRowLimit(rows?.title), [getScrollableRowLimit, height]);
    const shouldUseInnerScrollOnly = useMemo(() => {
        const expandedSections = tableData.filter((row) => isExpanded(row.title));
        const scrollableSections = expandedSections.filter(isScrollableSection);
        const hasExpandedInlineContent = expandedSections.some((row) => !isScrollableSection(row));
        return scrollableSections.length === 1 && !hasExpandedInlineContent;
    }, [isExpanded, isScrollableSection, tableData]);
    const getInnerTableHeight = useCallback((rows) => {
        const rowCount = rows?.data?.length ?? 0;
        if (rowCount === 0)
            return '300px';
        if (rowCount <= getScrollableRowLimit(rows?.title))
            return 'auto';
        if (!shouldUseInnerScrollOnly)
            return height;
        const headerHeight = isHeaderRequired && !isClientSide ? TABLE_HEADER_ROW_HEIGHT : 0;
        const titleRowsHeight = tableData.length * ACCORDION_TITLE_ROW_HEIGHT;
        return `calc(${height} - ${headerHeight + titleRowsHeight}px)`;
    }, [
        getScrollableRowLimit,
        height,
        isClientSide,
        isHeaderRequired,
        shouldUseInnerScrollOnly,
        tableData.length,
    ]);
    const handleStepGroupExpand = useCallback((rowData) => {
        if (!isStepGroupExpanded(rowData?.stepId)) {
            if (viewModeId)
                toggleViewRow(null);
            handleAccordion?.(rowData);
        }
        if (!loading) {
            setExpandStepGroup((prev) => {
                const newMap = new Map(prev);
                if (newMap.has(rowData?.stepId)) {
                    newMap.delete(rowData?.stepId);
                }
                else {
                    newMap.set(rowData?.stepId, true);
                }
                return newMap;
            });
        }
    }, [
        isStepGroupExpanded,
        viewModeId,
        toggleViewRow,
        handleAccordion,
        loading,
    ]);
    const getAccordionTableContent = useCallback((rows) => {
        if (rows.title === 'Steps' && !isViewPrivilegeMode) {
            return (jsx(StepInnerTable, { onHighlightComplete: onHighlightComplete, highlightKey: highlightKey, draggable: isDraggable, columns: tableMeta, onDragEnd: onDragEnd, data: rows.data, headerType: headerType, withCheckbox: true, editMode: editMode, editComponent: editComponent, noDataContent: noDataContent, NlpComponent: NlpComponent, AddNlp: AddNlp, tableType: rows.title, handleDragStart: () => {
                    expandStepGroup.clear();
                    handleDragStart?.();
                }, onSelect: handleRowCheckbox, selectedRows: selectedRows, viewModeId: viewModeId, ViewComponent: ViewComponent, handleClick: handleClick, handleStepGroupExpand: handleStepGroupExpand, isStepGroupExpanded: isStepGroupExpanded, stepPartialSelect: stepPartialSelect, height: getInnerTableHeight(rows), isClientSide: isClientSide }));
        }
        else {
            return (jsx(StepInnerTable, { onHighlightComplete: onHighlightComplete, highlightKey: highlightKey, draggable: false, editMode: editMode, withCheckbox: !isViewPrivilegeMode, editComponent: editComponent, columns: tableMeta, data: rows.data, headerType: headerType, noDataContent: noDataContent, tableType: rows.title, onSelect: handleRowCheckbox, selectedRows: selectedRows, viewModeId: viewModeId, ViewComponent: ViewComponent, handleClick: handleClick, handleStepGroupExpand: handleStepGroupExpand, isStepGroupExpanded: isStepGroupExpanded, isViewPrivilegeMode: isViewPrivilegeMode, height: getInnerTableHeight(rows), isClientSide: isClientSide }));
        }
    }, [
        isViewPrivilegeMode,
        onHighlightComplete,
        highlightKey,
        isDraggable,
        tableMeta,
        onDragEnd,
        headerType,
        editMode,
        editComponent,
        noDataContent,
        NlpComponent,
        AddNlp,
        expandStepGroup,
        handleDragStart,
        handleRowCheckbox,
        selectedRows,
        viewModeId,
        ViewComponent,
        handleClick,
        handleStepGroupExpand,
        isStepGroupExpanded,
        stepPartialSelect,
        tableData.length,
        getInnerTableHeight,
        isClientSide,
    ]);
    useImperativeHandle(ref, () => ({
        resetSelection: () => {
            setSelectedRows(Object.fromEntries(tableData.map((section) => [section.title, new Set()])));
            setStepPartialSelect(new Set());
        },
        handleUpdateCheckbox: (rowData, updatedTableData) => {
            const parentSpecialNlpId = rowData?.parentSpecialNlpId;
            const conditionSearchKey = rowData?.conditionSearchKey;
            if (parentSpecialNlpId || conditionSearchKey)
                if (updatedTableData) {
                    handleUpdateCheckboxState(updatedTableData, rowData, false);
                }
                else {
                    handleUpdateCheckboxState(tableData, rowData, false);
                }
        },
        deleteRow: (rowData) => {
            setSelectedRows((prev) => Object.fromEntries(Object.entries(prev)?.map(([key, ids]) => [
                key,
                new Set([...ids].filter((id) => id !== rowData?.stepId)),
            ])));
        },
        resetStepGroupAccordion: () => {
            setExpandStepGroup(new Map());
        },
    }), [tableData, handleUpdateCheckboxState]);
    useEffect(() => {
        if (!checkEmpty(AddNlp)) {
            setViewComponent(() => null);
            setViewModeId(null);
            if (AddNlp?.action === 'addLast') {
                onAccordionClick('Steps', 'open');
            }
        }
    }, [AddNlp]);
    return (jsxs("div", { style: { height }, className: classNames('ff-accordion-table-container-steps', {
            'ff-accordion-fixed-header-table': withFixedHeader,
        }), children: [isHeaderRequired && !isClientSide && (jsx("table", { cellSpacing: 0, className: classNames('ff-accordion-table', {
                    'ff-accordion-fixed-header': withFixedHeader,
                }), children: jsx("thead", { className: "table-thead", children: jsx("tr", { className: "ff-table-row", children: tableMeta.map((column, index) => (jsx("th", { style: { width: column?.width }, className: classNames('ff-table-header', headerType && `ff-accordion-table--${headerType}-bg`), children: jsx(Typography, { as: "div", fontWeight: "semi-bold", lineHeight: "18px", color: "var(--drawer-title-color)", children: column.header }) }, `${column.header}-${index}`))) }) }) })), jsx("div", { className: "ff-accordion-table-body", style: {
                    overflowY: shouldUseInnerScrollOnly ? 'hidden' : 'auto',
                }, children: tableData?.map((row) => {
                    const { title, data, actionCell, metaData } = row;
                    const totalRows = data.length;
                    const expanded = isExpanded(title);
                    const selectedCount = selectedRows[title]?.size ?? 0;
                    const showActionCell = selectedCount > 0 && totalRows > 0 && actionCell;
                    return (jsxs("div", { className: "column-table-accordion", children: [jsx(StepsTitle, { isViewPrivilegeMode: isViewPrivilegeMode, onAccordionClick: onAccordionClick, showActionCell: showActionCell, handleMainCheckbox: handleMainCheckbox, isAllSelected: isAllSelected, isPartialSelected: isPartialSelected, title: title, totalRows: totalRows, expanded: expanded, metaData: metaData, actionCell: actionCell, row: row, tableMeta: tableMeta, isHeaderRequired: isHeaderRequired, isBulkEnable: isBulkEnable, isClientSide: isClientSide, isMaximize: isMaximize }), expanded && getAccordionTableContent(row)] }, title));
                }) })] }));
}));
StepLandingTable.displayName = 'StepLandingTable';

export { StepLandingTable as default };
//# sourceMappingURL=StepLandingTable.js.map
