import { jsx, jsxs } from 'react/jsx-runtime';
import * as React from 'react';
import { useMemo } from 'react';
import classNames from '../../../../_virtual/index.js';
import { selectEntireColumn, dragStart, activate, setColumnPosition, setColumnWidth, dragEnd } from './actions.js';
import { get } from './matrix.js';
import useDispatch from './use-dispatch.js';
import useSelector from './use-selector.js';
import Typography from '../../../Typography/Typography.js';
import { getMatrixDimensions } from './util.js';

const ColumnIndicator = ({ column, label, selected, onSelect, setContextMenu, deleteColumn, addColumnLeft, addColumnRight, columnContextEnable, cell, selectedColumn, minimumColumnWidth, maxColLimit, disableDeleteOption, contextMenu, onAddColumn, onDeleteColumn, setVisibleRange, scrollToColumn, }) => {
    const dispatch = useDispatch();
    const excelData = useSelector((state) => state.model.data);
    const columnWidth = useSelector((state) => state.columnDimensions[column]?.width ?? minimumColumnWidth);
    const matrixData = useSelector((state) => state.model.data);
    const { columnCount } = getMatrixDimensions(matrixData);
    const updateVisibleRangeEnd = (action) => {
        setVisibleRange((prev) => {
            const value = {
                ...prev,
                end: action === 'increment' ? prev.end + 1 : prev.end - 1,
            };
            if (selectedColumn) {
                scrollToColumn(selectedColumn);
            }
            return value;
        });
    };
    const options = useMemo(() => {
        return [
            {
                label: 'Add Column Left',
                value: 'Add Column Left',
                iconName: 'plus_icon',
                action: () => {
                    updateVisibleRangeEnd('increment');
                    addColumnLeft(minimumColumnWidth);
                    onAddColumn?.(selectedColumn ?? column, true);
                },
                disableTooltip: 'Column limit reached',
                visible: cell?.contextDisable?.['Add Column Left'] ?? false,
                disable: columnCount >= maxColLimit,
            },
            {
                label: 'Add Column Right',
                value: 'Add Column Right',
                iconName: 'plus_icon',
                action: () => {
                    updateVisibleRangeEnd('increment');
                    addColumnRight(minimumColumnWidth);
                    onAddColumn?.(selectedColumn ?? column, false);
                },
                disableTooltip: 'Column limit reached',
                visible: cell?.contextDisable?.['Add Column Right'] ?? false,
                disable: columnCount >= maxColLimit,
            },
            ...(!disableDeleteOption
                ? [
                    {
                        label: 'Delete Column',
                        value: 'Delete Column',
                        iconName: 'delete',
                        action: () => {
                            updateVisibleRangeEnd('decrement');
                            deleteColumn();
                            onDeleteColumn?.(selectedColumn ?? column);
                        },
                        disableTooltip: '',
                        visible: cell?.contextDisable?.['Delete Column'] ?? false,
                        disable: false,
                    },
                ]
                : []),
        ];
    }, [selectedColumn, column, excelData]);
    const onMouseDrag = React.useCallback((event, isRight) => {
        const getTargetColumn = isRight ? column - 1 : column;
        const targetColumn = Math.max(getTargetColumn, 0);
        onSelect(targetColumn, event.shiftKey);
        const startX = event.clientX;
        const initialWidth = Number(columnWidth);
        const onMouseMove = (moveEvent) => {
            const delta = moveEvent.clientX - startX;
            const newWidth = Math.max(minimumColumnWidth, initialWidth + delta);
            dispatch(setColumnWidth(targetColumn, newWidth));
        };
        const onMouseUp = () => {
            document.removeEventListener('mousemove', onMouseMove);
            document.removeEventListener('mouseup', onMouseUp);
            dispatch(dragEnd());
        };
        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
        dispatch(dragStart());
    }, [column, columnWidth]);
    const activate$1 = React.useCallback((point) => dispatch(activate(point)), [dispatch]);
    const handleClick = React.useCallback((event) => {
        onSelect(column, event.shiftKey);
    }, [onSelect, column]);
    const contextClick = React.useCallback((event) => {
        event.preventDefault();
        onSelect(column, event.shiftKey);
        setContextMenu({
            open: columnContextEnable,
            contextType: 'column',
            options,
        });
    }, [column, selectedColumn, columnContextEnable, options]);
    React.useEffect(() => {
        if (selectedColumn !== undefined && contextMenu?.contextType === 'column') {
            setContextMenu((prev) => ({
                open: prev.open,
                contextType: 'column',
                options,
            }));
        }
    }, [
        column,
        selectedColumn,
        columnContextEnable,
        options,
        contextMenu?.contextType === 'column',
    ]);
    return (jsxs("th", { className: classNames('ff-spreadsheet-header', {
            'ff-spreadsheet-header--selected': selected,
        }), style: { width: `${columnWidth}px`, minWidth: '100px' }, onClick: handleClick, onContextMenu: contextClick, tabIndex: 0, children: [jsx(Typography, { fontWeight: "medium", children: label ?? columnIndexToLabel(column) }), jsx("div", { className: "drag-column-selector drag-column-left", onMouseDown: (e) => onMouseDrag(e, false), onDoubleClick: () => dispatch(setColumnPosition(column, columnWidth)), onClick: () => activate$1({ row: -1, column }) }), jsx("div", { className: "drag-column-selector drag-column-right", onMouseDown: (e) => onMouseDrag(e, true), onDoubleClick: () => dispatch(setColumnPosition(column, columnWidth)), onClick: () => activate$1({ row: -1, column }) })] }, column));
};
const enhance = (ColumnIndicatorComponent) => {
    return function ColumnIndicatorWrapper(props) {
        const dispatch = useDispatch();
        const selectEntireColumn$1 = React.useCallback((column, extend) => dispatch(selectEntireColumn(column, extend)), [dispatch]);
        const selected = useSelector((state) => state.selected.hasEntireColumn(props.column));
        const selectedColumn = useSelector((state) => state.selectedColumn ?? undefined);
        const cell = useSelector((state) => state.active ? get(state.active, state.model.data) : undefined);
        return (jsx(ColumnIndicatorComponent, { ...props, cell: cell, selected: selected, selectedColumn: selectedColumn, onSelect: selectEntireColumn$1, scrollToColumn: props.scrollToColumn }));
    };
};
const EnhancedColumnIndicator = enhance(ColumnIndicator);
function columnIndexToLabel(column) {
    let label = '';
    let index = column;
    while (index >= 0) {
        label = String.fromCharCode(65 + (index % 26)) + label;
        index = Math.floor(index / 26) - 1;
    }
    return label;
}

export { EnhancedColumnIndicator as default, enhance };
//# sourceMappingURL=ColumnIndicator.js.map
