import $i18n from '../../../../../../../locales/i18n.js';
import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import { CnIcon, CnInputTextArea, CnButton } from '@cainiaofe/cn-ui';
import { Popup } from '@cainiaofe/cn-domain-popup';
import { useAiTableIcons } from '../../../../../../../cn-ai-table/view/hooks/use-ai-table-icons';
import { armsHottagLog } from '../../../../../../../utils/arms/arms-hot-tag-log.js';
import './ai-cell-actions.scss';
/**
 * AI 单元格操作按钮组件
 * 选中 AI 单元格时，在单元格外部右边显示操作按钮
 * 点击展开按钮时弹出编辑/预览弹窗
 */
export const AiCellActions = ({ visible, position, cellLeft = 0, cellValue = '', fieldName, onSave, onRegenerate, }) => {
    const icons = useAiTableIcons();
    const [popupVisible, setPopupVisible] = useState(false);
    const [mode, setMode] = useState('edit');
    const [editValue, setEditValue] = useState(cellValue);
    // 使用 ref 保存最新的 editValue，避免闭包问题
    const editValueRef = useRef(editValue);
    // 使用 ref 保存初始的 cellValue，用于比较是否有变化
    const initialCellValueRef = useRef(cellValue);
    // 同步外部 cellValue 变化
    useEffect(() => {
        setEditValue(cellValue);
        editValueRef.current = cellValue;
        initialCellValueRef.current = cellValue;
    }, [cellValue]);
    // 当 visible 变为 false 时，关闭弹窗
    useEffect(() => {
        if (!visible) {
            setPopupVisible(false);
        }
    }, [visible]);
    // 当弹窗打开时，重置初始值引用
    useEffect(() => {
        if (popupVisible) {
            initialCellValueRef.current = editValueRef.current;
        }
    }, [popupVisible]);
    // 处理弹窗关闭，自动保存
    const handlePopupVisibleChange = (newVisible) => {
        // 当弹窗从打开变为关闭时，自动保存
        if (popupVisible && !newVisible && mode === 'edit') {
            // 使用 ref 获取最新的值，避免闭包问题
            const latestValue = editValueRef.current;
            const initialValue = initialCellValueRef.current;
            // 如果值有变化，则保存
            if (latestValue !== initialValue) {
                armsHottagLog({
                    hottag: 'cn-ai-table.aiField.save',
                    name: $i18n.get({ id: 'Save', dm: '保存' }),
                    c6: fieldName,
                });
                onSave === null || onSave === void 0 ? void 0 : onSave(latestValue);
            }
        }
        setPopupVisible(newVisible);
    };
    if (!visible)
        return null;
    // 弹窗内容
    const popupContent = (React.createElement("div", { className: "ai-cell-content-popup", onClick: (e) => e.stopPropagation() },
        React.createElement("div", { className: "ai-cell-content-popup-header" },
            React.createElement("div", { className: "ai-cell-content-popup-title" },
                React.createElement("img", { src: icons.FIELD_AI, alt: $i18n.get({ id: 'AIField', dm: 'AI字段' }), style: { width: '16px', height: '16px' } }),
                React.createElement("span", null, fieldName || $i18n.get({ id: 'AIField.55YiI', dm: 'AI 字段' }))),
            React.createElement("div", { className: "ai-cell-content-popup-tabs" },
                React.createElement(CnButton, { type: "normal", onClick: () => {
                        const newMode = mode === 'preview' ? 'edit' : 'preview';
                        armsHottagLog({
                            hottag: newMode === 'edit'
                                ? 'cn-ai-table.aiField.switchToEdit'
                                : 'cn-ai-table.aiField.switchToPreview',
                            name: newMode === 'edit'
                                ? $i18n.get({ id: 'SwitchToEdit', dm: '切换到编辑' })
                                : $i18n.get({ id: 'SwitchToPreview', dm: '切换到预览' }),
                            c6: fieldName,
                        });
                        setMode(newMode);
                    } }, mode === 'edit'
                    ? $i18n.get({ id: 'Preview', dm: '预览' })
                    : $i18n.get({ id: 'Edit', dm: '编辑' }))),
            React.createElement(CnIcon, { type: "close", size: "small", className: "ai-cell-content-popup-close", onClick: () => handlePopupVisibleChange(false) })),
        React.createElement("div", { className: "ai-cell-content-popup-body" },
            React.createElement(CnInputTextArea, { value: editValue, style: { width: '100%' }, onChange: (val) => {
                    const newValue = val;
                    setEditValue(newValue);
                    // 同步更新 ref，确保保存时能获取到最新值
                    editValueRef.current = newValue;
                }, placeholder: $i18n.get({ id: 'PleaseEnterContent.TvWOC', dm: '请输入内容' }), autoHeight: { minRows: 10, maxRows: 20 }, readOnly: mode === 'preview' }))));
    const content = (React.createElement("div", { className: "ai-cell-actions", style: {
            top: position.top,
            left: position.left,
        } },
        React.createElement("span", { style: { display: 'contents' }, onClick: (e) => e.stopPropagation(), onPointerDown: (e) => e.stopPropagation() },
            React.createElement(Popup, { visible: popupVisible, onVisibleChange: handlePopupVisibleChange, triggerType: "click", align: "br", offset: { mainAxis: 20, crossAxis: -20 }, trigger: React.createElement(CnIcon, { type: "eye", className: "ai-cell-actions-btn" }) }, popupContent)),
        React.createElement(CnIcon, { type: "refresh", className: "ai-cell-actions-btn", onClick: (e) => {
                e.stopPropagation();
                armsHottagLog({
                    hottag: 'cn-ai-table.aiField.regenerate',
                    name: $i18n.get({ id: 'Regenerate', dm: '重新生成' }),
                    c6: fieldName,
                });
                onRegenerate === null || onRegenerate === void 0 ? void 0 : onRegenerate();
            } })));
    // 挂载到 body，避免菜包等场景下父级 transform/overflow 导致 position:fixed 相对错误容器而错位
    if (typeof document !== 'undefined' && document.body) {
        return ReactDOM.createPortal(content, document.body);
    }
    return content;
};
export default AiCellActions;
