// Filename: frontend/js/pages/logs/logList.js
import { modalManager } from '../../components/ui.js';

export default class LogSettingsModal {
    constructor({ onSave }) {
        this.modalId = 'log-settings-modal';
        this.onSave = onSave;
        const modal = document.getElementById(this.modalId);
        if (!modal) {
            throw new Error(`Modal with id "${this.modalId}" not found.`);
        }
        
        this.elements = {
            modal: modal,
            title: document.getElementById('log-settings-modal-title'),
            saveBtn: document.getElementById('log-settings-save-btn'),
            
            logLevelSelect: document.getElementById('log-level-select'),
            
            cleanupEnableToggle: document.getElementById('log-cleanup-enable'),
            cleanupSettingsPanel: document.getElementById('log-cleanup-settings'),
            cleanupRetentionInput: document.getElementById('log-cleanup-retention-days'),
            retentionDaysGroup: document.getElementById('retention-days-group'),
            retentionPresetBtns: document.querySelectorAll('#retention-days-group button[data-days]'),
            cleanupExecTimeInput: document.getElementById('log-cleanup-exec-time'), // [NEW] 添加时间选择器元素
        };

        this.activePresetClasses = ['!bg-primary', '!text-primary-foreground', '!border-primary', 'hover:!bg-primary/90'];
        this.inactivePresetClasses = ['modal-btn-secondary'];
        this._initEventListeners();
    }

    open(settingsData = {}) {
        this._populateForm(settingsData);
        modalManager.show(this.modalId);
    }

    close() {
        modalManager.hide(this.modalId);
    }

    _initEventListeners() {
        this.elements.saveBtn.addEventListener('click', this._handleSave.bind(this));
        
        this.elements.cleanupEnableToggle.addEventListener('change', (e) => {
            this.elements.cleanupSettingsPanel.classList.toggle('hidden', !e.target.checked);
        });

        this._initRetentionPresets();

        const closeAction = () => this.close();
        const closeTriggers = this.elements.modal.querySelectorAll(`[data-modal-close="${this.modalId}"]`);
        closeTriggers.forEach(trigger => trigger.addEventListener('click', closeAction));
        this.elements.modal.addEventListener('click', (event) => {
            if (event.target === this.elements.modal) closeAction();
        });
    }
    
    _initRetentionPresets() {
        this.elements.retentionPresetBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const days = btn.dataset.days;
                this.elements.cleanupRetentionInput.value = days;
                this._updateActivePresetButton(days);
            });
        });

        this.elements.cleanupRetentionInput.addEventListener('input', (e) => {
            this._updateActivePresetButton(e.target.value);
        });
    }

    _updateActivePresetButton(currentValue) {
        this.elements.retentionPresetBtns.forEach(btn => {
            if (btn.dataset.days === currentValue) {
                btn.classList.remove(...this.inactivePresetClasses);
                btn.classList.add(...this.activePresetClasses);
            } else {
                btn.classList.remove(...this.activePresetClasses);
                btn.classList.add(...this.inactivePresetClasses);
            }
        });
    }

    async _handleSave() {
        const data = this._collectFormData();
        if (data.auto_cleanup.enabled && (!data.auto_cleanup.retention_days || data.auto_cleanup.retention_days <= 0)) {
            alert('启用自动清理时，保留天数必须是大于0的数字。');
            return;
        }

        if (this.onSave) {
            this.elements.saveBtn.disabled = true;
            this.elements.saveBtn.textContent = '保存中...';
            try {
                await this.onSave(data);
                this.close();
            } catch (error) {
                console.error("Failed to save log settings:", error);
                // 可以添加一个UI提示，比如 toast
            } finally {
                this.elements.saveBtn.disabled = false;
                this.elements.saveBtn.textContent = '保存设置';
            }
        }
    }
    
    // [MODIFIED] - 更新此方法以填充新的时间选择器
    _populateForm(data) {
        this.elements.logLevelSelect.value = data.log_level || 'INFO';
        
        const cleanup = data.auto_cleanup || {};
        const isCleanupEnabled = cleanup.enabled || false;
        this.elements.cleanupEnableToggle.checked = isCleanupEnabled;
        this.elements.cleanupSettingsPanel.classList.toggle('hidden', !isCleanupEnabled);
        
        const retentionDays = cleanup.retention_days || '';
        this.elements.cleanupRetentionInput.value = retentionDays;
        this._updateActivePresetButton(retentionDays.toString());

        // [NEW] 填充执行时间，提供一个安全的默认值
        this.elements.cleanupExecTimeInput.value = cleanup.exec_time || '04:05'; 
    }

    // [MODIFIED] - 更新此方法以收集新的时间数据
    _collectFormData() {
        const parseIntOrNull = (value) => {
            const trimmed = value.trim();
            if (trimmed === '') return null;
            const num = parseInt(trimmed, 10);
            return isNaN(num) ? null : num;
        };

        const isCleanupEnabled = this.elements.cleanupEnableToggle.checked;

        const formData = {
            log_level: this.elements.logLevelSelect.value,
            auto_cleanup: {
                enabled: isCleanupEnabled,
                interval: isCleanupEnabled ? 'daily' : null, 
                retention_days: isCleanupEnabled ? parseIntOrNull(this.elements.cleanupRetentionInput.value) : null,
                exec_time: isCleanupEnabled ? this.elements.cleanupExecTimeInput.value : '04:05', // [NEW] 收集时间数据
            },
        };
        
        return formData;      
    }
}
