import { useContext, useEffect, useMemo, useRef, useState, } from 'react';
import { redirectToLink } from '../../../utils/redirectToLink';
import { DataGridContext } from '../../DataGridContext';
import { Variant } from '../../enums';
import { DISABLE_ROW_ATTR } from '../constants';
import { RowContext } from '../RowContext';
import { useMobileLogic } from './hooks';
import { mergeColumnsOptions } from './utils';
export const useLogic = ({ keyId, columns, row, nestedChildren, level, variant, options, isInitialExpanded = false, expandedLevel, isSelectable, selectedRows, onSelectRow, onRowClick, isVisibleCollapseButton, registerRowElement, unregisterRowElement, style, }) => {
    const { isDrawerOpen, handleOpenDrawer, handleCloseDrawer } = useMobileLogic();
    const isDefaultExpanded = isInitialExpanded && level <= expandedLevel - 1 && nestedChildren?.length;
    const { checkIsOpened, toggleOpenItems } = useContext(DataGridContext);
    const { isDisabled, disabledReason } = useContext(RowContext);
    const savedElementRef = useRef(null);
    const rowRef = (element) => {
        if (element) {
            savedElementRef.current = element;
            registerRowElement?.(rowId, element);
        }
        else if (savedElementRef.current) {
            unregisterRowElement?.(rowId, savedElementRef.current);
            savedElementRef.current = null;
        }
    };
    const [isVisibleTooltip, setVisibleTooltip] = useState(false);
    const rowId = row[keyId];
    const { isDisabled: isExternalDisabled, disabledReason: externalDisabledReason, href, target, } = options || {};
    const disabled = isDisabled || isExternalDisabled;
    const isOpen = checkIsOpened(rowId);
    const handleRowClick = () => {
        if (disabled) {
            handleOpenDrawer();
            return undefined;
        }
        if (href) {
            return redirectToLink(href, target);
        }
        onRowClick?.(row);
    };
    useEffect(() => {
        // Проверка на isOpen необходима для infinite версии с виртуализацией, когда происходит размонтировании компонента
        if (isDefaultExpanded && !isOpen) {
            toggleOpenItems(rowId);
        }
    }, []);
    const isChecked = isSelectable &&
        Boolean(selectedRows?.find((selectedRow) => selectedRow[keyId] === rowId));
    const isShowConnector = Object.is(variant, Variant.Tree);
    const childrenColumns = useMemo(() => mergeColumnsOptions(columns, options?.childrenColumns), [columns, options]);
    const handleToggle = (event) => {
        event.stopPropagation();
        toggleOpenItems(rowId);
    };
    const handleOpenTooltip = (event) => {
        const element = event.target;
        const isDisabledCell = element?.getAttribute(DISABLE_ROW_ATTR) === 'true';
        if (isDisabledCell) {
            setVisibleTooltip(true);
        }
    };
    const handleCloseTooltip = () => setVisibleTooltip(false);
    const handleMouseMove = (event) => {
        if (!disabled) {
            return;
        }
        const element = event.target;
        const isDisabledCell = element.getAttribute(DISABLE_ROW_ATTR) === 'true';
        if (!isDisabledCell) {
            setVisibleTooltip(false);
        }
    };
    const isRenderCollapseButton = Boolean(nestedChildren?.length) && isVisibleCollapseButton;
    const rowStyles = useMemo(() => ({
        '--level': level,
        ...style,
    }), [level, style]);
    const isHovered = Boolean(!disabled && (onRowClick || href));
    const disabledReasonText = externalDisabledReason || disabledReason;
    return {
        disabledReasonText,
        rowStyles,
        isOpen,
        isShowConnector,
        childrenColumns,
        rowId,
        rowRef,
        disabled,
        isRenderCollapseButton,
        handleToggle,
        isHovered,
        rowProps: {
            onClick: handleRowClick,
            onMouseMove: handleMouseMove,
        },
        drawerProps: {
            open: isDrawerOpen,
            onClose: handleCloseDrawer,
            title: 'Заблокировано',
        },
        tooltipProps: {
            open: isVisibleTooltip,
            title: disabled ? disabledReasonText : undefined,
            onOpen: handleOpenTooltip,
            onClose: handleCloseTooltip,
        },
        checkboxProps: {
            checked: isChecked,
            disabled,
            onChange: onSelectRow(row),
        },
        nestedChildrenProps: {
            isOpen,
            rowId,
        },
    };
};
