import React, { useCallback, useMemo, useRef, useState } from 'react';
import classnames from 'classnames';
import { DndItemTypes } from '../../types';
import { DefaultCellRenderer } from '../../helpers';
import { useStyles } from './styles';
import { useDndMonitor, useDroppable } from '@dnd-kit/core';
import { ColumnDragIndicator } from './ColumnDragIndicator';
export var TableCellWithDnd = function (_a) {
    var _b;
    var columnValue = _a.columnValue, rowData = _a.rowData, index = _a.index, shouldRenderDragIndicator = _a.shouldRenderDragIndicator, setHoveredColumn = _a.setHoveredColumn, resetHoveredColumn = _a.resetHoveredColumn, rowIsDragging = _a.rowIsDragging;
    var styles = useStyles();
    var _c = useState(false), enableDropForColumn = _c[0], setEnableDropForColumn = _c[1];
    var _d = useState(false), isColumnDragging = _d[0], setIsColumnDragging = _d[1];
    useDndMonitor({
        onDragStart: function (event) {
            if (event.active.data.current.type === DndItemTypes.Column) {
                setEnableDropForColumn(true);
                setIsColumnDragging(event.active.id === columnValue.id);
            }
        },
        onDragEnd: function () {
            setEnableDropForColumn(false);
            setIsColumnDragging(false);
        }
    });
    var setDroppableNodeRef = useDroppable({
        id: columnValue.id
    }).setNodeRef;
    var columnRef = useRef(null);
    var setColumnRef = useCallback(function (elem) {
        setDroppableNodeRef(elem);
        columnRef.current = elem;
    }, [setDroppableNodeRef]);
    var getColumnWidth = function () { var _a; return (_a = columnRef === null || columnRef === void 0 ? void 0 : columnRef.current) === null || _a === void 0 ? void 0 : _a.offsetWidth; };
    var CellRenderer = rowData.cellRenderer || DefaultCellRenderer;
    var onMouseOver = setHoveredColumn ? function () { return setHoveredColumn(columnValue); } : undefined;
    var draggingColumnStyle = useMemo(function () { return ({ opacity: isColumnDragging ? 0 : 1 }); }, [isColumnDragging]);
    return (React.createElement("td", { style: draggingColumnStyle, ref: enableDropForColumn ? setColumnRef : undefined, className: styles.tableData, onMouseOver: onMouseOver, onMouseLeave: resetHoveredColumn },
        React.createElement("div", { className: classnames((_b = {}, _b[styles.hidden] = rowIsDragging, _b)) },
            shouldRenderDragIndicator && (React.createElement(ColumnDragIndicator, { columnValue: columnValue, rowData: rowData, index: index, getColumnWidth: getColumnWidth })),
            React.createElement(CellRenderer, { value: columnValue[rowData.id] }))));
};
