import React, { useState } from 'react';

// 定义输入框信息类型
interface InputInfo {
    id: string;
    name: string;
    type: string;
    value: string;
    placeholder: string;
}

// 定义自动发送消息的配置
interface AutoSendConfig {
    inputSelector: string;
    buttonSelector: string;
    messages: string[];
}

export default function AutoOptions() {
    const [inputs, setInputs] = useState<InputInfo[]>([]);
    const [showInputs, setShowInputs] = useState(false);
    const [autoSendConfig, setAutoSendConfig] = useState<AutoSendConfig>({
        inputSelector: '.semi-input-textarea',  // 设置默认输入框选择器
        buttonSelector: '#flow-end-msg-send',   // 设置默认按钮选择器
        messages: Array.from({ length: 10 }, (_, i) => {
            const num = i + 1;
            return num === 1 ? ['0', num.toString()] : [`0${num - 1}`, num.toString()];
        }).flat() // 生成 ["0", "1", "01", "2", "02", "3", ..., "09", "10"]
    });
    const [isAutoSending, setIsAutoSending] = useState(false);
    const [autoSendResults, setAutoSendResults] = useState<any[]>([]);

    // 自动发送消息
    const autoSendMessages = async () => {
        setIsAutoSending(true);
        setAutoSendResults([]);

        try {
            const [tab] = await browser.tabs.query({ active: true, currentWindow: true });

            if (tab.id) {
                const response = await browser.tabs.sendMessage(tab.id, {
                    action: "autoSendMessages",
                    ...autoSendConfig
                });

                if (response.success) {
                    setAutoSendResults(response.results);
                } else {
                    console.error('自动发送消息失败:', response.error);
                }
            }
        } catch (error) {
            console.error('自动发送消息出错:', error);
        } finally {
            setIsAutoSending(false);
        }
    };

    // 更新自动发送配置
    const updateAutoSendConfig = (field: keyof AutoSendConfig, value: string | string[]) => {
        setAutoSendConfig(prev => ({
            ...prev,
            [field]: value
        }));
    };

    return (
        <>
            <div>
                <h1>页面分析工具</h1>

                {/* 自动发送消息配置区域 */}
                <div style={{ marginTop: '20px', padding: '10px', border: '1px solid #ccc', borderRadius: '4px' }}>
                    <h2>自动发送消息</h2>
                    <div style={{ marginBottom: '10px' }}>
                        <label>
                            输入框选择器:
                            <input
                                type="text"
                                value={autoSendConfig.inputSelector}
                                onChange={(e) => updateAutoSendConfig('inputSelector', e.target.value)}
                                placeholder="例如: #message-input 或 .input-class"
                                style={{ width: '100%', padding: '5px', marginTop: '5px' }}
                            />
                        </label>
                    </div>
                    <div style={{ marginBottom: '10px' }}>
                        <label>
                            发送按钮选择器:
                            <input
                                type="text"
                                value={autoSendConfig.buttonSelector}
                                onChange={(e) => updateAutoSendConfig('buttonSelector', e.target.value)}
                                placeholder="例如: #send-button 或 .send-btn"
                                style={{ width: '100%', padding: '5px', marginTop: '5px' }}
                            />
                        </label>
                    </div>
                    <div style={{ marginBottom: '10px' }}>
                        <label>
                            消息列表 (每行一条):
                            <textarea
                                value={autoSendConfig.messages.join('\n')}
                                onChange={(e) => updateAutoSendConfig('messages', e.target.value.split('\n').filter(msg => msg.trim()))}
                                placeholder="每行输入一条消息"
                                rows={5}
                                style={{ width: '100%', padding: '5px', marginTop: '5px' }}
                            />
                        </label>
                    </div>
                    <button
                        onClick={autoSendMessages}
                        disabled={isAutoSending || !autoSendConfig.inputSelector || !autoSendConfig.buttonSelector}
                        style={{
                            padding: '8px 16px',
                            backgroundColor: isAutoSending ? '#6c757d' : '#28a745',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: isAutoSending ? 'not-allowed' : 'pointer'
                        }}
                    >
                        {isAutoSending ? '发送中...' : '开始自动发送'}
                    </button>

                    {/* 显示发送结果 */}
                    {autoSendResults.length > 0 && (
                        <div style={{ marginTop: '10px' }}>
                            <h3>发送结果:</h3>
                            <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
                                {autoSendResults.map((result, index) => (
                                    <div
                                        key={index}
                                        style={{
                                            padding: '5px',
                                            marginBottom: '5px',
                                            backgroundColor: result.status === 'sent' ? '#d4edda' : '#f8d7da',
                                            borderRadius: '3px'
                                        }}
                                    >
                                        <span>[{new Date(result.timestamp).toLocaleTimeString()}] </span>
                                        <span>消息: {result.message} - </span>
                                        <span style={{ fontWeight: 'bold' }}>
                                            {result.status === 'sent' ? '已发送' : '发送失败'}
                                        </span>
                                        {result.error && <span> (错误: {result.error})</span>}
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>

                {showInputs && (
                    <div style={{ marginTop: '20px' }}>
                        <h2>页面输入框 ({inputs.length} 个):</h2>
                        {inputs.length > 0 ? (
                            <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
                                {inputs.map((input, index) => (
                                    <div
                                        key={index}
                                        style={{
                                            padding: '10px',
                                            border: '1px solid #eee',
                                            marginBottom: '10px',
                                            borderRadius: '4px'
                                        }}
                                    >
                                        <div><strong>ID:</strong> {input.id || '无'}</div>
                                        <div><strong>Name:</strong> {input.name || '无'}</div>
                                        <div><strong>Type:</strong> {input.type}</div>
                                        <div><strong>Placeholder:</strong> {input.placeholder || '无'}</div>
                                        <div><strong>Value:</strong> {input.value || '无'}</div>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <p>未找到输入框元素</p>
                        )}
                        <button
                            onClick={() => setShowInputs(false)}
                            style={{
                                padding: '8px 16px',
                                backgroundColor: '#6c757d',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: 'pointer'
                            }}
                        >
                            隐藏输入框信息
                        </button>
                    </div>
                )}
            </div>
        </>
    );
}



