import $i18n from '../../locales/i18n.js';
import * as React from 'react';
import { armsHottagLog } from '../../utils/arms/arms-hot-tag-log.js';
import { emitCellSelectEvent } from '../../cn-ai-table/view/components/views/table-view/utils/cell-event-utils';
import { useCnAiListEventNames } from '../../cn-ai-agent/context/cn-ai-list-event-context';
/**
 * 单元格编辑功能 Hook
 * @param onSave 保存回调函数，参数为 (rowId, columnId, value, originalRow)
 * @param columns 列配置数组，用于提取格式化后的显示值
 */
export function useCellEditing(onSave, columns) {
    const cnAiListEventNames = useCnAiListEventNames();
    // 编辑状态：正在编辑的单元格
    const [editingCell, setEditingCell] = React.useState(null);
    // 编辑值
    const [editingValue, setEditingValue] = React.useState('');
    // 处理单元格点击事件
    const handleCellClick = React.useCallback((rowId, columnId, currentValue, originalRow, event) => {
        event.stopPropagation(); // 阻止事件冒泡
        armsHottagLog({
            hottag: 'cn-ai-table.cell.clickEdit',
            name: $i18n.get({ id: 'ClickEdit', dm: '点击编辑' }),
            c6: rowId,
            c7: columnId,
        });
        setEditingCell({ rowId, columnId, originalRow });
        const valueStr = currentValue != null ? String(currentValue) : '';
        setEditingValue(valueStr);
        // 触发自定义事件，通知 AI Agent 组件单元格被选中（使用工具函数）
        emitCellSelectEvent(columnId, currentValue, originalRow, rowId, event, undefined, columns, cnAiListEventNames);
    }, [columns, cnAiListEventNames]);
    // 自动调整 textarea 高度的 effect
    React.useEffect(() => {
        if (editingCell) {
            // 延迟执行，确保 textarea 已渲染
            setTimeout(() => {
                const textarea = document.querySelector('.ai-table-cell-input');
                if (textarea) {
                    textarea.style.height = 'auto';
                    textarea.style.height = `${textarea.scrollHeight}px`;
                }
            }, 0);
        }
    }, [editingCell, editingValue]);
    // 处理 textarea 内容变化，自动调整高度
    const handleTextareaChange = React.useCallback((e) => {
        setEditingValue(e.target.value);
        // 自动调整高度
        e.target.style.height = 'auto';
        e.target.style.height = `${e.target.scrollHeight}px`;
    }, []);
    // 处理输入框失去焦点，保存数据
    const handleCellBlur = React.useCallback(() => {
        if (editingCell && onSave) {
            armsHottagLog({
                hottag: 'cn-ai-table.cell.save',
                name: $i18n.get({ id: 'Save', dm: '保存' }),
                c6: editingCell.rowId,
                c7: editingCell.columnId,
            });
            onSave(editingCell.rowId, editingCell.columnId, editingValue, editingCell.originalRow);
        }
        setEditingCell(null);
        setEditingValue('');
    }, [editingCell, editingValue, onSave]);
    // 处理 textarea 键盘事件
    const handleTextareaKeyDown = React.useCallback((e) => {
        // Ctrl+Enter 或 Cmd+Enter 保存
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
            e.preventDefault();
            if (editingCell && onSave) {
                armsHottagLog({
                    hottag: 'cn-ai-table.cell.save',
                    name: $i18n.get({ id: 'Save', dm: '保存' }),
                    c6: editingCell.rowId,
                    c7: editingCell.columnId,
                });
                onSave(editingCell.rowId, editingCell.columnId, editingValue, editingCell.originalRow);
            }
            setEditingCell(null);
            setEditingValue('');
        }
        else if (e.key === 'Escape') {
            armsHottagLog({
                hottag: 'cn-ai-table.cell.cancelEdit',
                name: $i18n.get({ id: 'CancelEdit', dm: '取消编辑' }),
            });
            setEditingCell(null);
            setEditingValue('');
        }
        // 普通 Enter 键允许换行，不阻止默认行为
    }, [editingCell, editingValue, onSave]);
    // 判断单元格是否正在编辑
    const isEditing = React.useCallback((rowId, columnId) => {
        return (editingCell === null || editingCell === void 0 ? void 0 : editingCell.rowId) === rowId && (editingCell === null || editingCell === void 0 ? void 0 : editingCell.columnId) === columnId;
    }, [editingCell]);
    return {
        editingCell: editingCell,
        editingValue,
        setEditingValue,
        setEditingCell,
        handleCellClick,
        handleTextareaChange,
        handleCellBlur,
        handleTextareaKeyDown,
        isEditing,
    };
}
