import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment, memo, useCallback } from 'react';
import { BottomDrawer } from '../../BottomDrawer';
import { Checkbox } from '../../Checkbox';
import { Tooltip } from '../../Tooltip';
import { checkIsDeepEqual } from '../../utils/checkIsDeepEqual';
import { classNames } from '../../utils/classNames';
import { cva } from '../../utils/cva';
import { getInertProps } from '../../utils/getInertProps';
import { dataGridCellClassnames } from '../Cell';
import { isGroupColumns } from '../utils';
import { DISABLE_ROW_ATTR, dataGridGroupedColumnLabelClassnames, dataGridRowClassnames, dataGridRowContentClassnames, } from './constants';
import { NestedChildren } from './NestedChildren';
import { BottomDrawerContent, CellStyled, CheckboxCell, ChevronIcon, CollapseButton, CollapseCell, ContentWrapper, GroupedColumnLabel, Wrapper, } from './styles';
import { useLogic } from './useLogic';
import { checkIsDisabled } from './utils';
const rootCva = cva(dataGridRowClassnames.root, {
    variants: {
        isShowConnector: {
            true: dataGridRowClassnames.showConnector,
        },
    },
});
const rowContentCva = cva(dataGridRowContentClassnames.root, {
    variants: {
        isHovered: {
            true: dataGridRowContentClassnames.hovered,
        },
    },
});
const groupedColumnLabelCva = cva(dataGridGroupedColumnLabelClassnames.root, {
    variants: {
        hidden: {
            true: dataGridGroupedColumnLabelClassnames.hidden,
        },
    },
});
const RowComponent = (props) => {
    const { isOpen, isShowConnector, childrenColumns, rowId, handleToggle, checkboxProps, rowProps, isHovered, tooltipProps, nestedChildrenProps, disabled, isRenderCollapseButton, rowRef, rowStyles, drawerProps, disabledReasonText, } = useLogic(props);
    const { className, row, options, variant, isSelectable, gridColumns, isInitialExpanded, expandedLevel, level, nestedChildren, initialVisibleChildrenCount, moreButtonColumnPosition, isVisibleCollapseButton, columns, emptyCellValue, selectedRows, activeRowId, keyId, onSelectRow, onRowClick, sectionOffset, totalColumnsCount, registerRowElement, unregisterRowElement, onRowEnter, onRowLeave, style, 
    // В этот rest-оператор попадают специфичные пропсы (атрибуты) virtuoso
    // Необходимы для DataGridInfinite
    ...selfProps } = props;
    const { isDisabledLastCell = true, isNotSelectable } = options || {};
    const renderStartAdornment = () => {
        if (!isRenderCollapseButton && (!isSelectable || isNotSelectable)) {
            return null;
        }
        return (_jsxs(_Fragment, { children: [isRenderCollapseButton && (_jsx(CollapseCell, { children: _jsx(CollapseButton, { variant: "text", onClick: handleToggle, children: _jsx(ChevronIcon, { "$isActive": isOpen }) }) })), isSelectable && !isNotSelectable && (_jsx(CheckboxCell, { ...getInertProps(disabled), onClick: (event) => event.stopPropagation(), className: dataGridRowClassnames.checkbox, children: _jsx(Checkbox, { ...checkboxProps }) }))] }));
    };
    const renderCells = useCallback(() => {
        const lastCellGlobalIndex = (totalColumnsCount ?? columns.length) - 1;
        const availableCellsByIndex = !isDisabledLastCell
            ? [lastCellGlobalIndex]
            : undefined;
        return columns?.map((cell, index) => {
            const cellId = `${rowId}-${index}`;
            const globalIndex = (sectionOffset ?? 0) + index;
            const isDisabledCell = checkIsDisabled(disabled, availableCellsByIndex, globalIndex);
            const isFirstCell = globalIndex === 0;
            if (isGroupColumns(cell)) {
                const { label, children, hideTitleOnMobile, isHideOnMobile } = cell;
                return (_jsxs(Fragment, { children: [_jsx(GroupedColumnLabel, { variant: "caption", color: "grey", colorIntensity: "700", className: groupedColumnLabelCva({
                                hidden: hideTitleOnMobile || isHideOnMobile,
                            }), children: label }), children.map((child, childIndex) => {
                            const childCellId = `${cellId}-${childIndex}`;
                            const shouldRenderStartAdornment = isFirstCell && childIndex === 0;
                            return (_jsx(CellStyled, { row: row, cell: child, isHideOnMobile: isHideOnMobile, emptyCellValue: emptyCellValue, isDisabled: isDisabledCell, startAdornment: shouldRenderStartAdornment && renderStartAdornment(), isHidePersonalData: child.isHidePersonalData, className: dataGridCellClassnames.grouped }, childCellId));
                        })] }, cellId));
            }
            return (_jsx(CellStyled, { row: row, cell: cell, emptyCellValue: emptyCellValue, startAdornment: isFirstCell && renderStartAdornment(), isDisabled: isDisabledCell, isHidePersonalData: cell.isHidePersonalData }, cellId));
        });
    }, [
        isOpen,
        columns,
        disabled,
        checkboxProps.checked,
        totalColumnsCount,
        sectionOffset,
    ]);
    const renderRow = useCallback(({ key, ...nestedRowProps }) => (_jsx(Row, { keyId: keyId, ...nestedRowProps, variant: variant, isSelectable: isSelectable, selectedRows: selectedRows, gridColumns: gridColumns, isInitialExpanded: isInitialExpanded, expandedLevel: expandedLevel, initialVisibleChildrenCount: initialVisibleChildrenCount, moreButtonColumnPosition: moreButtonColumnPosition, isVisibleCollapseButton: isVisibleCollapseButton, activeRowId: activeRowId, columns: childrenColumns, onSelectRow: onSelectRow, onRowClick: onRowClick, totalColumnsCount: totalColumnsCount, registerRowElement: registerRowElement, unregisterRowElement: unregisterRowElement, onRowEnter: onRowEnter, onRowLeave: onRowLeave, sectionOffset: sectionOffset }, key)), [
        keyId,
        variant,
        isSelectable,
        selectedRows,
        gridColumns,
        isInitialExpanded,
        expandedLevel,
        initialVisibleChildrenCount,
        moreButtonColumnPosition,
        sectionOffset,
        totalColumnsCount,
        activeRowId,
        childrenColumns,
        onSelectRow,
        onRowClick,
        registerRowElement,
        unregisterRowElement,
        onRowEnter,
        onRowLeave,
    ]);
    return (_jsxs(Wrapper, { className: classNames(className, rootCva({ isShowConnector })), style: rowStyles, ...selfProps, children: [_jsx(Tooltip, { followCursor: true, arrow: false, ...tooltipProps, children: _jsx(ContentWrapper, { "data-row-id": rowId, ref: rowRef, onPointerEnter: () => onRowEnter?.(rowId), onPointerLeave: (event) => onRowLeave?.(rowId, event.nativeEvent), className: rowContentCva({ isHovered }), "$gridColumns": gridColumns, [DISABLE_ROW_ATTR]: disabled, ...rowProps, children: renderCells() }) }), _jsx(NestedChildren, { ...nestedChildrenProps, data: nestedChildren, keyId: keyId, level: level, variant: variant, gridColumns: gridColumns, initialVisibleChildrenCount: initialVisibleChildrenCount, moreButtonColumnPosition: moreButtonColumnPosition, 
                // biome-ignore lint/suspicious/noTsIgnore: <>
                // @ts-ignore
                renderRow: renderRow }), _jsx(BottomDrawer, { ...drawerProps, children: _jsx(BottomDrawerContent, { children: disabledReasonText }) })] }));
};
const arePropsEqual = (prevProps, nextProps) => {
    const deepEqualityProps = new Set(['row']);
    // Список пропсов, которые нужно игнорировать при сравнении
    const skipProps = new Set([
        'selectedRows',
        'onSelectRow',
        'columns',
    ]);
    const keys = Object.keys(prevProps);
    return keys.every((key) => {
        const typedKey = key;
        // Не сравниваем свойства, которые нужно пропустить
        if (skipProps.has(typedKey)) {
            return true;
        }
        const prevValue = prevProps[typedKey];
        const nextValue = nextProps[typedKey];
        if (deepEqualityProps.has(typedKey)) {
            return checkIsDeepEqual(prevValue, nextValue);
        }
        return prevValue === nextValue;
    });
};
export const Row = memo(RowComponent, arePropsEqual);
