// Filename: frontend/js/pages/keys/deleteGroupModal.js

import { modalManager } from '../../components/ui.js';
import { apiFetch } from '../../services/api.js'; 
import { toastManager } from '../../components/taskCenter.js';

export default class DeleteGroupModal {
    constructor({ onDeleteSuccess }) {
        this.modalId = 'delete-group-modal';
        this.onDeleteSuccess = onDeleteSuccess;
        this.activeGroup = null;
        this.elements = {
            modal: document.getElementById(this.modalId),
            title: document.getElementById('delete-group-modal-title'),
            confirmInput: document.getElementById('delete-group-confirm-input'),
            confirmBtn: document.getElementById('delete-group-confirm-btn'),
        };
        if (!this.elements.modal) {
            throw new Error(`Modal with id "${this.modalId}" not found.`);
        }
        this._initEventListeners();
    }
    open(group) {
        if (!group || !group.id) {
            console.error("Cannot open DeleteGroupModal: group object with id is required.");
            return;
        }
        this.activeGroup = group;
        this.elements.title.innerHTML = `确认删除分组 <code class="text-base font-semibold text-red-500">${group.display_name}</code>`;
        this._reset();
        modalManager.show(this.modalId);
    }
    _initEventListeners() {
        this.elements.confirmBtn?.addEventListener('click', this._handleSubmit.bind(this));
        this.elements.confirmInput?.addEventListener('input', () => {
            const isConfirmed = this.elements.confirmInput.value.trim() === '删除';
            this.elements.confirmBtn.disabled = !isConfirmed;
        });
        const closeAction = () => {
            this._reset();
            modalManager.hide(this.modalId);
        };
        
        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();
        });
    }
    async _handleSubmit() {
        if (!this.activeGroup) return;
        this.elements.confirmBtn.disabled = true;
        this.elements.confirmBtn.innerHTML = `<i class="fas fa-spinner fa-spin mr-2"></i>删除中...`;
        try {
            // [FIX] Use apiFetch directly to call the backend endpoint.
            const endpoint = `/admin/keygroups/${this.activeGroup.id}`;
            const response = await apiFetch(endpoint, {
                method: 'DELETE',
                noCache: true // Ensure a fresh request
            });
            
            const result = await response.json(); // Parse the JSON response
            if (result.success) {
                toastManager.show(`分组 '${this.activeGroup.display_name}' 已成功删除。`, 'success');
                if (this.onDeleteSuccess) {
                    this.onDeleteSuccess(this.activeGroup.id);
                }
                modalManager.hide(this.modalId);
            } else {
                // Use the error message from the backend response
                throw new Error(result.error?.message || result.message || '删除失败，请稍后再试。');
            }
        } catch (error) {
            toastManager.show(`删除失败: ${error.message}`, 'error');
        } finally {
            // We do a full reset in finally to ensure the button state is always correct.
            this._reset();
        }
    }
  
    _reset() {
        if (this.elements.confirmInput) this.elements.confirmInput.value = '';
        if (this.elements.confirmBtn) {
            this.elements.confirmBtn.disabled = true;
            this.elements.confirmBtn.innerHTML = '确认删除';
        }
    }
}
