import { jsx, jsxs } from 'react/jsx-runtime';
import { isFunction } from '../../assets/utils/functionUtils.js';
import classNames from '../../_virtual/index.js';
import Checkbox from '../Checkbox/Checkbox.js';
import Typography from '../Typography/Typography.js';
import { DndContext, closestCorners } from '../../node_modules/.pnpm/@dnd-kit_core@6.3.1_react-d_dd28f9613915b34fadb5fb09ef9e129f/node_modules/@dnd-kit/core/dist/core.esm.js';
import { restrictToVerticalAxis } from '../../node_modules/.pnpm/@dnd-kit_modifiers@9.0.0_@d_29804ea7af5102b7c3fb5f8ff91223c9/node_modules/@dnd-kit/modifiers/dist/modifiers.esm.js';
import { SortableContext, verticalListSortingStrategy } from '../../node_modules/.pnpm/@dnd-kit_sortable@8.0.0_@dn_d0203b85309944898f6a8d832beb8e74/node_modules/@dnd-kit/sortable/dist/sortable.esm.js';
import { forwardRef, useRef, useState, useEffect, useImperativeHandle, isValidElement, cloneElement } from 'react';
import DraggableTableRow from './components/DraggableTableRow.js';
import { appendNewRow } from '../../utils/AppendNewRow/AppendNewRow.js';
import { scrollToView } from '../../utils/ScrollToview/ScrollToView.js';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty.js';

const PrePostTable = forwardRef(({ data = [], columns = [], headerType, withCheckbox = false, onSelect, allSelected, partialSelected = false, withFixedHeader = true, borderWithRadius = false, headerCheckboxDisabled = false, noDataContent, height = '100%', className = '', tableHeadClass = '', tableBodyRowClass = '', headerTextColor, tableDataTextColor, draggable = false, onDragEnd, loadMore = () => { }, editMode = '', editComponent, NlpComponent, AddNlp, handleDragStart, handleViewComponent, handleAccordion, loading, scriptType = false, }, ref) => {
    const observerRef = useRef(null);
    const [ViewComponent, setViewComponent] = useState(null);
    const [viewModeId, setViewModeId] = useState(null);
    const toggleViewRow = (row) => {
        setViewModeId((prev) => (prev === row?.stepId ? null : row?.stepId));
    };
    const handleClick = (item) => {
        toggleViewRow(item);
        const Component = handleViewComponent?.(item, toggleViewRow);
        if (Component) {
            setViewComponent(() => Component);
        }
        else {
            toggleViewRow(null);
        }
    };
    const [expandStepGroup, setExpandStepGroup] = useState(new Map());
    const isStepGroupExpanded = (stepId) => expandStepGroup.has(stepId);
    const handleStepGroupExpand = (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;
            });
        }
    };
    // const resetStepGroupAccordion = () => {
    //   setExpandStepGroup(new Map());
    // };
    useEffect(() => {
        const scrollContainer = document.getElementById('ff-table-scroll-container');
        const firstNode = document.getElementById('ff-table-first-node');
        const lastNode = document.getElementById('ff-table-last-node');
        // Exit early if data is empty or elements are missing
        if (!scrollContainer || !firstNode || !lastNode || !data?.length) {
            return;
        }
        observerRef.current = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    const direction = entry.target.id === 'ff-table-last-node' ? 'below' : 'above';
                    loadMore(direction);
                }
            });
        }, {
            root: scrollContainer,
            rootMargin: '8px',
            threshold: 0.1,
        });
        observerRef.current.observe(firstNode);
        observerRef.current.observe(lastNode);
        return () => {
            observerRef.current?.disconnect();
        };
    }, [data, loadMore]);
    const handleOnclick = (column, row, index) => {
        let { onClick, accessor } = column;
        if (onClick && isFunction(onClick)) {
            onClick(accessor, row, index);
        }
    };
    const onSelectClick = (e, item) => {
        if (onSelect) {
            onSelect(e, item);
        }
    };
    const handleDragEnd = (event) => {
        const { active, over } = event;
        if (!over || active.id === over.id)
            return;
        const oldIndex = data.findIndex((item) => item._id === active.id || item.stepId === active.id);
        const newIndex = data.findIndex((item) => item._id === over.id || item.stepId === over.id);
        if (oldIndex === -1 || newIndex === -1)
            return;
        if (onDragEnd)
            onDragEnd(oldIndex, newIndex);
    };
    useEffect(() => {
        scrollToView('getInFocus');
    }, [AddNlp, viewModeId]);
    if (ref) {
        useImperativeHandle(ref, () => ({
            resetStepGroupAccordion: () => {
                setExpandStepGroup(new Map());
            },
        }));
    }
    return (jsx(DndContext, { collisionDetection: closestCorners, onDragStart: () => {
            handleDragStart?.();
            expandStepGroup.clear();
        }, onDragEnd: handleDragEnd, modifiers: [restrictToVerticalAxis], children: jsx(SortableContext, { disabled: !draggable, items: data?.map((row) => row.stepId || row._id), strategy: verticalListSortingStrategy, children: jsxs("div", { style: { height: height }, id: "ff-table-scroll-container", className: classNames(className, {
                    'pre-fixed-header-table': withFixedHeader,
                    'pre-border-borderRadius': borderWithRadius,
                }), children: [jsxs("table", { className: classNames(`ff-table-pre-post`), cellSpacing: 0, children: [jsx("thead", { className: classNames({
                                    'pre-table-thead': withFixedHeader,
                                }, tableHeadClass), children: jsx("tr", { children: columns.map((column, index) => (jsx("th", { className: classNames(`${headerType && `${headerType}-bg`}`, `${headerTextColor && `${headerTextColor}-color`}`), style: { width: column?.width }, children: jsxs(Typography, { as: "div", fontWeight: "semi-bold", className: "ff-label-checkbox-container", lineHeight: "18px", color: "var(--drawer-title-color)", children: [index === 0 && withCheckbox && (jsx("span", { className: "ff-table-pre-post-checkbox", children: jsx(Checkbox, { onChange: (e) => {
                                                            onSelectClick(e, {
                                                                allSelected: e.target.checked,
                                                            });
                                                        }, checked: allSelected !== undefined ? allSelected : false, partial: !!partialSelected, disabled: headerCheckboxDisabled }) })), column.header] }) }, column.header))) }) }), jsxs("tbody", { className: "pre-table-tbody", children: [jsx("tr", { id: "ff-table-first-node" }), appendNewRow(data, AddNlp ?? {})?.map((row, index) => {
                                        const isEdit = editMode === row.stepId;
                                        const isEditOrNew = isEdit || row.isNew;
                                        const renderEditableRow = () => (jsxs("tr", { id: "getInFocus", className: "pre-edit-row", children: [isEdit && isValidElement(editComponent) && (jsx("td", { colSpan: columns.length, children: cloneElement(editComponent, {
                                                        rowData: row,
                                                        rowIndex: index + 1,
                                                    }) })), row.isNew &&
                                                    !isEdit &&
                                                    isValidElement(NlpComponent) && (jsx("td", { colSpan: columns.length, children: cloneElement(NlpComponent, {
                                                        rowIndex: index,
                                                        rowData: row,
                                                    }) }))] }, row.stepId || index));
                                        const renderSortableRow = () => (jsx(DraggableTableRow, { row: row, indexNumber: index, columns: columns, tableBodyRowClass: tableBodyRowClass, handleOnclick: handleOnclick, tableDataTextColor: tableDataTextColor, withCheckbox: withCheckbox, onSelectClick: onSelectClick, draggable: draggable, dataLength: data?.length, viewModeId: viewModeId, ViewComponent: ViewComponent, handleClick: handleClick, handleStepGroupExpand: handleStepGroupExpand, isStepGroupExpanded: isStepGroupExpanded, scriptType: scriptType }));
                                        return isEditOrNew
                                            ? renderEditableRow()
                                            : renderSortableRow();
                                    }), jsx("tr", { id: "ff-table-last-node" })] })] }), checkEmpty(data) && checkEmpty(AddNlp) && (jsx("div", { className: "ff-no-data-content", style: { height: `calc(${height} - 50px)` }, children: noDataContent }))] }) }) }));
});

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