import * as React from 'react';
import { useState, useCallback, useMemo, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { CnIcon, CnTab, CnTabItem } from '@cainiaofe/cn-ui';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragOverlay, } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, horizontalListSortingStrategy, } from '@dnd-kit/sortable';
import classNames from 'classnames';
import './cn-drag-tab.scss';
const SortableTabWrapper = ({ id, children }) => {
    const { attributes, listeners, setNodeRef, isDragging } = useSortable({ id });
    return (React.createElement("div", { ref: setNodeRef, className: classNames('cn-drag-tab__sortable-wrapper', {
            'cn-drag-tab__sortable-wrapper--dragging': isDragging,
        }), ...attributes, ...listeners }, children));
};
SortableTabWrapper.displayName = 'SortableTabWrapper';
/**
 * Portal wrapper: renders DragOverlay into document.body to escape
 * ancestors with `filter: blur(0px)` (e.g. cn-ui-page) which create
 * a containing block that breaks `position: fixed` overlay positioning.
 */
function PortaledDragOverlay({ children, ...props }) {
    return createPortal(React.createElement(DragOverlay, { ...props }, children), document.body);
}
const TabContent = ({ icon, title, closeable, onClose }) => {
    const handleClose = (e) => {
        e.stopPropagation();
        onClose === null || onClose === void 0 ? void 0 : onClose();
    };
    return (React.createElement("div", { className: "cn-next-tabs-tab-inner" },
        React.createElement("div", { className: "cn-ui-tab-inner-sub cn-ui-tab-inner-sub-left" }),
        React.createElement("div", { className: "cn-ui-tab-inner-sub cn-ui-tab-inner-sub-right" }),
        icon,
        title,
        closeable && (React.createElement(CnIcon, { outerClassName: "cn-next-tabs-tab-close", size: "small", type: "close", onClick: handleClose }))));
};
TabContent.displayName = 'TabContent';
export const CnDragTab = (props) => {
    var _a, _b;
    const { items, onDragStart: onDragStartProp, onDragOver: onDragOverProp, onDragCancel: onDragCancelProp, onDragEnd, disableDrag = false, className, activeKey: controlledActiveKey, defaultActiveKey, onChange, ...restTabProps } = props;
    const isControlled = controlledActiveKey !== undefined;
    const [internalActiveKey, setInternalActiveKey] = useState(String((_b = defaultActiveKey !== null && defaultActiveKey !== void 0 ? defaultActiveKey : (_a = items[0]) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : ''));
    const [draggingItem, setDraggingItem] = useState(null);
    // 非受控模式：items 变化时，若当前 activeKey 不再存在则回退到首项
    useEffect(() => {
        if (isControlled)
            return;
        const currentKeyExists = items.some((item) => String(item.key) === internalActiveKey);
        if (!currentKeyExists && items.length > 0) {
            const fallbackKey = String(items[0].key);
            setInternalActiveKey(fallbackKey);
            onChange === null || onChange === void 0 ? void 0 : onChange(fallbackKey);
        }
    }, [items, isControlled, internalActiveKey, onChange]);
    const activeKey = isControlled ? String(controlledActiveKey) : internalActiveKey;
    const handleTabChange = useCallback((key) => {
        const normalized = String(key);
        if (!isControlled) {
            setInternalActiveKey(normalized);
        }
        onChange === null || onChange === void 0 ? void 0 : onChange(normalized);
    }, [isControlled, onChange]);
    const sensors = useSensors(useSensor(PointerSensor, {
        activationConstraint: {
            distance: 5,
        },
    }), useSensor(KeyboardSensor, {
        coordinateGetter: sortableKeyboardCoordinates,
    }));
    const itemKeys = useMemo(() => items.filter((item) => !item.disableDrag).map((item) => String(item.key)), [items]);
    const itemMap = useMemo(() => {
        const map = new Map();
        items.forEach((item) => map.set(String(item.key), item));
        return map;
    }, [items]);
    const handleDragStart = useCallback((event) => {
        const { active } = event;
        const item = itemMap.get(String(active.id));
        setDraggingItem(item || null);
        onDragStartProp === null || onDragStartProp === void 0 ? void 0 : onDragStartProp(event);
    }, [itemMap, onDragStartProp]);
    const handleDragOver = useCallback((event) => {
        onDragOverProp === null || onDragOverProp === void 0 ? void 0 : onDragOverProp(event);
    }, [onDragOverProp]);
    const handleDragCancel = useCallback(() => {
        setDraggingItem(null);
        onDragCancelProp === null || onDragCancelProp === void 0 ? void 0 : onDragCancelProp();
    }, [onDragCancelProp]);
    const handleDragEnd = useCallback((event) => {
        const { active, over } = event;
        setDraggingItem(null);
        if (!over || active.id === over.id) {
            return;
        }
        const dragActiveKey = String(active.id);
        const overKey = String(over.id);
        const oldIndex = items.findIndex((item) => String(item.key) === dragActiveKey);
        const newIndex = items.findIndex((item) => String(item.key) === overKey);
        if (oldIndex === -1 || newIndex === -1) {
            return;
        }
        const newItems = arrayMove(items, oldIndex, newIndex);
        onDragEnd === null || onDragEnd === void 0 ? void 0 : onDragEnd({
            activeKey: dragActiveKey,
            overKey,
            oldIndex,
            newIndex,
            newItems,
        });
    }, [items, onDragEnd]);
    const draggableTabRender = useCallback((key, tabProps) => {
        const normalizedKey = String(key);
        const item = itemMap.get(normalizedKey);
        const { icon, title, closeable, onClose } = tabProps;
        if (item === null || item === void 0 ? void 0 : item.disableDrag) {
            return (React.createElement(TabContent, { icon: icon, title: title, closeable: closeable, onClose: () => onClose === null || onClose === void 0 ? void 0 : onClose(normalizedKey) }));
        }
        return (React.createElement(SortableTabWrapper, { id: normalizedKey },
            React.createElement(TabContent, { icon: icon, title: title, closeable: closeable, onClose: () => onClose === null || onClose === void 0 ? void 0 : onClose(normalizedKey) })));
    }, [itemMap]);
    const tabItemNodes = useMemo(() => items.map((item) => (React.createElement(CnTabItem, { key: item.key, title: item.title, disabled: item.disabled, closeable: item.closeable, icon: item.icon, ...item.tabItemProps }, item.children))), [items]);
    if (disableDrag) {
        return (React.createElement(CnTab, { ...restTabProps, className: classNames('cn-drag-tab', className), activeKey: activeKey, onChange: handleTabChange }, tabItemNodes));
    }
    return (React.createElement("div", { className: "cn-drag-tab-container" },
        React.createElement(DndContext, { sensors: sensors, collisionDetection: closestCenter, onDragStart: handleDragStart, onDragOver: handleDragOver, onDragCancel: handleDragCancel, onDragEnd: handleDragEnd },
            React.createElement(SortableContext, { items: itemKeys, strategy: horizontalListSortingStrategy },
                React.createElement(CnTab, { ...restTabProps, className: classNames('cn-drag-tab', className), activeKey: activeKey, onChange: handleTabChange, tabRender: draggableTabRender }, tabItemNodes)),
            React.createElement(PortaledDragOverlay, { dropAnimation: null }, draggingItem && (React.createElement("div", { className: "cn-drag-tab__overlay" },
                React.createElement(TabContent, { icon: draggingItem.icon, title: draggingItem.title })))))));
};
CnDragTab.displayName = 'CnDragTab';
