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

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

export default class CloneGroupModal {
    constructor({ onCloneSuccess }) {
        this.modalId = 'clone-group-modal';
        this.onCloneSuccess = onCloneSuccess;
        this.activeGroup = null;

        this.elements = {
            modal: document.getElementById(this.modalId),
            title: document.getElementById('clone-group-modal-title'),
            confirmBtn: document.getElementById('clone-group-confirm-btn'),
        };

        if (!this.elements.modal) {
            console.error(`Modal with id "${this.modalId}" not found. Ensure the HTML is in your document.`);
            return;
        }
        this._initEventListeners();
    }

    open(group) {
        if (!group || !group.id) {
            console.error("Cannot open CloneGroupModal: a group object with an ID is required.");
            return;
        }
        this.activeGroup = group;
        this.elements.title.innerHTML = `确认克隆分组 <code class="text-base font-semibold text-blue-500">${group.display_name}</code>`;
        this._reset();
        modalManager.show(this.modalId);
    }

    _initEventListeners() {
        this.elements.confirmBtn?.addEventListener('click', this._handleSubmit.bind(this));
        
        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 {
            const endpoint = `/admin/keygroups/${this.activeGroup.id}/clone`;
            const response = await apiFetch(endpoint, {
                method: 'POST',
                noCache: true
            });

            const result = await response.json();

            if (result.success && result.data) {
                toastManager.show(`分组 '${this.activeGroup.display_name}' 已成功克隆。`, 'success');
                if (this.onCloneSuccess) {
                    // Pass the entire new group object back to the main controller.
                    this.onCloneSuccess(result.data);
                }
                modalManager.hide(this.modalId);
            } else {
                throw new Error(result.error?.message || result.message || '克隆失败，请稍后再试。');
            }
        } catch (error) {
            toastManager.show(`克隆失败: ${error.message}`, 'error');
        } finally {
            this._reset();
        }
    }

    _reset() {
        if (this.elements.confirmBtn) {
            this.elements.confirmBtn.disabled = false;
            this.elements.confirmBtn.innerHTML = '确认克隆';
        }
    }
}
