import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { isFunction } from '../../assets/utils/functionUtils';
import classNames from 'classnames';
import './PrePostTable.scss';
import Checkbox from '../Checkbox';
import Typography from '../Typography';
import { closestCorners, DndContext } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import { SortableContext, verticalListSortingStrategy, } from '@dnd-kit/sortable';
import { useEffect, useRef, cloneElement, isValidElement, useState, forwardRef, useImperativeHandle, } from 'react';
import DraggableTableRow from './components/DraggableTableRow';
import { appendNewRow } from '../../utils/AppendNewRow/AppendNewRow';
import { scrollToView } from '../../utils/ScrollToview/ScrollToView';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty';
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 default PrePostTable;
//# sourceMappingURL=PrePostTable.js.map