/**
 * InsertrFormRenderer - Form renderer using markdown-first approach
 * Thin wrapper around the Editor system
 */
import { Editor } from './editor.js';

export class InsertrFormRenderer {
    constructor(apiClient = null) {
        this.apiClient = apiClient;
        this.editor = new Editor();
    }

    /**
     * Show edit form for any content element
     * @param {Object} meta - Element metadata {element, contentId, contentType}
     * @param {string|Object} currentContent - Current content value
     * @param {Function} onSave - Save callback
     * @param {Function} onCancel - Cancel callback
     */
    showEditForm(meta, currentContent, onSave, onCancel) {
        const { element } = meta;

        // Handle insertr-group elements by getting their viable children
        if (element.classList.contains('insertr-group')) {
            const children = this.getGroupChildren(element);
            const groupMeta = { ...meta, element: children };
            return this.editor.edit(groupMeta, currentContent, onSave, onCancel);
        }

        // All other elements use the editor directly
        return this.editor.edit(meta, currentContent, onSave, onCancel);
    }

    /**
     * Get viable children from group element
     */
    getGroupChildren(groupElement) {
        const children = [];
        for (const child of groupElement.children) {
            // Skip elements that don't have meaningful text content
            if (child.textContent.trim().length > 0) {
                children.push(child);
            }
        }
        return children;
    }

    /**
     * Close current form
     */
    closeForm() {
        this.editor.close();
    }

    /**
     * Show version history modal (placeholder for future implementation)
     */
    async showVersionHistory(contentId, element, onRestore) {
        try {
            // Get version history from API
            const apiClient = this.getApiClient();
            if (!apiClient) {
                console.warn('No API client configured for version history');
                return;
            }

            const versions = await apiClient.getContentVersions(contentId);
            
            // Create version history modal
            const historyModal = this.createVersionHistoryModal(contentId, versions, onRestore);
            document.body.appendChild(historyModal);
            
            // Setup handlers
            this.setupVersionHistoryHandlers(historyModal, contentId);

        } catch (error) {
            console.error('Failed to load version history:', error);
            this.showVersionHistoryError('Failed to load version history. Please try again.');
        }
    }

    /**
     * Create version history modal (simplified placeholder)
     */
    createVersionHistoryModal(contentId, versions, onRestore) {
        const modal = document.createElement('div');
        modal.className = 'insertr-version-modal';
        
        let versionsHTML = '';
        if (versions && versions.length > 0) {
            versionsHTML = versions.map((version, index) => `
                <div class="insertr-version-item" data-version-id="${version.version_id}">
                    <div class="insertr-version-meta">
                        <span class="insertr-version-label">${index === 0 ? 'Previous Version' : `Version ${versions.length - index}`}</span>
                        <span class="insertr-version-date">${this.formatDate(version.created_at)}</span>
                        ${version.created_by ? `<span class="insertr-version-user">by ${version.created_by}</span>` : ''}
                    </div>
                    <div class="insertr-version-content">${this.escapeHtml(this.truncateContent(version.value, 100))}</div>
                    <div class="insertr-version-actions">
                        <button type="button" class="insertr-btn-restore" data-version-id="${version.version_id}">Restore</button>
                        <button type="button" class="insertr-btn-view-diff" data-version-id="${version.version_id}">View Full</button>
                    </div>
                </div>
            `).join('');
        } else {
            versionsHTML = '<div class="insertr-version-empty">No previous versions found</div>';
        }

        modal.innerHTML = `
            <div class="insertr-version-backdrop">
                <div class="insertr-version-content-modal">
                    <div class="insertr-version-header">
                        <h3>Version History</h3>
                        <button type="button" class="insertr-btn-close">&times;</button>
                    </div>
                    <div class="insertr-version-list">
                        ${versionsHTML}
                    </div>
                </div>
            </div>
        `;

        return modal;
    }

    /**
     * Setup version history modal handlers
     */
    setupVersionHistoryHandlers(modal, contentId) {
        const closeBtn = modal.querySelector('.insertr-btn-close');
        const backdrop = modal.querySelector('.insertr-version-backdrop');
        
        // Close handlers
        if (closeBtn) {
            closeBtn.addEventListener('click', () => modal.remove());
        }
        
        backdrop.addEventListener('click', (e) => {
            if (e.target === backdrop) {
                modal.remove();
            }
        });

        // Restore handlers
        const restoreButtons = modal.querySelectorAll('.insertr-btn-restore');
        restoreButtons.forEach(btn => {
            btn.addEventListener('click', async () => {
                const versionId = btn.getAttribute('data-version-id');
                if (await this.confirmRestore()) {
                    await this.restoreVersion(contentId, versionId);
                    modal.remove();
                    this.closeForm();
                }
            });
        });

        // View diff handlers
        const viewButtons = modal.querySelectorAll('.insertr-btn-view-diff');
        viewButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const versionId = btn.getAttribute('data-version-id');
                this.showVersionDetails(versionId);
            });
        });
    }

    /**
     * Helper methods for version history
     */
    formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diff = now - date;
        
        // Less than 24 hours ago
        if (diff < 24 * 60 * 60 * 1000) {
            const hours = Math.floor(diff / (60 * 60 * 1000));
            if (hours < 1) {
                const minutes = Math.floor(diff / (60 * 1000));
                return `${minutes}m ago`;
            }
            return `${hours}h ago`;
        }
        
        // Less than 7 days ago
        if (diff < 7 * 24 * 60 * 60 * 1000) {
            const days = Math.floor(diff / (24 * 60 * 60 * 1000));
            return `${days}d ago`;
        }
        
        // Older - show actual date
        return date.toLocaleDateString();
    }

    truncateContent(content, maxLength) {
        if (content.length <= maxLength) return content;
        return content.substring(0, maxLength) + '...';
    }

    async confirmRestore() {
        return confirm('Are you sure you want to restore this version? This will replace the current content.');
    }

    async restoreVersion(contentId, versionId) {
        try {
            const apiClient = this.getApiClient();
            await apiClient.rollbackContent(contentId, versionId);
            return true;
        } catch (error) {
            console.error('Failed to restore version:', error);
            alert('Failed to restore version. Please try again.');
            return false;
        }
    }

    showVersionDetails(versionId) {
        // TODO: Implement detailed version view with diff
        alert(`Version details not implemented yet (Version ID: ${versionId})`);
    }

    showVersionHistoryError(message) {
        alert(message);
    }

    // Helper to get API client
    getApiClient() {
        return this.apiClient || window.insertrAPIClient || null;
    }

    /**
     * Escape HTML to prevent XSS
     */
    escapeHtml(text) {
        if (typeof text !== 'string') return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }


}