import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Copy, TrashBin } from '@gravity-ui/icons';
import { Button, Card, Icon } from '@gravity-ui/uikit';
import * as React from 'react';
import { editorCn } from "../../utils/cn.js";
import { DragContext } from "./DragContext.js";
import './TreeItem.css';
const b = editorCn('tree-item');
export const Item = ({ type, children, treeTitle, path, selected, onCopy, onDelete, onSelect, onReorder, }) => {
    const { draggedItem, setDraggedItem, showPreview, hidePreview } = React.useContext(DragContext);
    const [isDragging, setIsDragging] = React.useState(false);
    const [isDragOver, setIsDragOver] = React.useState(false);
    const [mouseDownPos, setMouseDownPos] = React.useState(null);
    const itemRef = React.useRef(null);
    // Scroll into view when selected
    React.useEffect(() => {
        if (selected && itemRef.current) {
            itemRef.current.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest',
            });
        }
    }, [selected]);
    const handleCopy = React.useCallback(() => {
        onCopy(path);
    }, [onCopy, path]);
    const handleDelete = React.useCallback(() => {
        onDelete(path);
    }, [onDelete, path]);
    const handleMouseDown = React.useCallback((e) => {
        setMouseDownPos({ x: e.clientX, y: e.clientY });
    }, []);
    const handleMouseUp = React.useCallback((e) => {
        if (mouseDownPos) {
            // Check if the mouse has moved significantly (dragging) or just a click
            const dx = Math.abs(e.clientX - mouseDownPos.x);
            const dy = Math.abs(e.clientY - mouseDownPos.y);
            // If the mouse hasn't moved much, consider it a click for selection
            if (dx < 5 && dy < 5) {
                e.stopPropagation();
                onSelect(path);
            }
        }
        setMouseDownPos(null);
    }, [mouseDownPos, onSelect, path]);
    const handleDragStart = React.useCallback((e) => {
        e.stopPropagation();
        const dragData = {
            path,
            type,
            treeTitle,
        };
        e.dataTransfer.setData('application/json', JSON.stringify(dragData));
        // eslint-disable-next-line no-not-accumulator-reassign/no-not-accumulator-reassign, no-param-reassign
        e.dataTransfer.effectAllowed = 'move';
        setIsDragging(true);
        // Update drag context
        setDraggedItem(dragData);
    }, [path, type, treeTitle, setDraggedItem]);
    const handleDragEnd = React.useCallback(() => {
        setIsDragging(false);
        // Reset drag context
        setDraggedItem(null);
        hidePreview();
    }, [setDraggedItem, hidePreview]);
    const handleDragOver = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        // eslint-disable-next-line no-not-accumulator-reassign/no-not-accumulator-reassign, no-param-reassign
        e.dataTransfer.dropEffect = 'move';
        setIsDragOver(true);
        const rect = e.currentTarget.getBoundingClientRect();
        if (draggedItem) {
            showPreview(rect, draggedItem);
        }
    }, [showPreview, draggedItem]);
    const handleDragLeave = React.useCallback(() => {
        setIsDragOver(false);
        hidePreview();
    }, [hidePreview]);
    const handleDrop = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
        try {
            const data = e.dataTransfer.getData('application/json');
            if (data) {
                const dragItem = JSON.parse(data);
                if (dragItem.path.join(',') !== path.join(',')) {
                    onReorder(dragItem.path, path);
                    // Reset drag context
                    setDraggedItem(null);
                    hidePreview();
                }
            }
        }
        catch (error) {
            // eslint-disable-next-line no-console
            console.error('Error parsing drag data:', error);
        }
    }, [onReorder, path, setDraggedItem, hidePreview]);
    const handleChildrenFirstPositionDrop = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        try {
            const data = e.dataTransfer.getData('application/json');
            if (data) {
                const dragItem = JSON.parse(data);
                // Create a path for the first child position
                const firstChildPath = [...path, 0];
                // Reorder to the first position within children
                onReorder(dragItem.path, firstChildPath, 'prepend');
                // Reset drag context
                setDraggedItem(null);
                hidePreview();
            }
        }
        catch (error) {
            // eslint-disable-next-line no-console
            console.error('Error parsing drag data:', error);
        }
    }, [onReorder, path, setDraggedItem, hidePreview]);
    const handleDropZoneDragOver = (e) => {
        e.preventDefault();
        e.stopPropagation();
        // eslint-disable-next-line no-not-accumulator-reassign/no-not-accumulator-reassign, no-param-reassign
        e.dataTransfer.dropEffect = 'move';
        // Show preview element at this position
        const rect = e.currentTarget.getBoundingClientRect();
        if (draggedItem) {
            showPreview(rect, draggedItem);
        }
    };
    return (_jsxs(Card, { ref: itemRef, className: b({
            selected,
            dragging: isDragging,
            'drag-over': isDragOver,
        }), onMouseDown: handleMouseDown, onMouseUp: handleMouseUp, draggable: true, onDragStart: handleDragStart, onDragEnd: handleDragEnd, onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, children: [_jsxs("div", { className: b('main'), children: [_jsxs("div", { className: b('text'), children: [_jsx("div", { className: b('type'), children: type }), _jsx("div", { className: b('title'), children: treeTitle })] }), _jsxs("div", { className: b('buttons'), children: [_jsx(Button, { view: "flat", size: "xs", onClick: handleCopy, children: _jsx(Icon, { size: 12, data: Copy }) }), _jsx(Button, { view: "flat", size: "xs", onClick: handleDelete, children: _jsx(Icon, { size: 12, data: TrashBin }) })] })] }), children && (_jsxs(React.Fragment, { children: [_jsx("div", { className: b('children-drop-zone'), onDragOver: handleDropZoneDragOver, onDragLeave: hidePreview, onDrop: handleChildrenFirstPositionDrop }), children] }))] }));
};
//# sourceMappingURL=TreeItem.js.map
