/**
 * 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();
        this.setupStyles();
    }

    /**
     * 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;
    }

    /**
     * Setup form styles (consolidated and simplified)
     */
    setupStyles() {
        const styles = `
            /* Overlay and Form Container */
            .insertr-form-overlay {
                position: absolute;
                z-index: 10000;
            }

            .insertr-edit-form {
                background: white;
                border: 2px solid #007cba;
                border-radius: 8px;
                padding: 1rem;
                box-shadow: 0 8px 25px rgba(0,0,0,0.15);
                width: 100%;
                box-sizing: border-box;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                min-width: 600px;
                max-width: 800px;
            }

            /* Form Header */
            .insertr-form-header {
                font-weight: 600;
                color: #1f2937;
                margin-bottom: 1rem;
                padding-bottom: 0.5rem;
                border-bottom: 1px solid #e5e7eb;
                font-size: 0.875rem;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }

            /* Form Groups and Fields */
            .insertr-form-group {
                margin-bottom: 1rem;
            }

            .insertr-form-group:last-child {
                margin-bottom: 0;
            }

            .insertr-form-label {
                display: block;
                font-weight: 600;
                color: #374151;
                margin-bottom: 0.5rem;
                font-size: 0.875rem;
            }

            .insertr-form-input, 
            .insertr-form-textarea {
                width: 100%;
                padding: 0.75rem;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                font-family: inherit;
                font-size: 1rem;
                transition: border-color 0.2s, box-shadow 0.2s;
                box-sizing: border-box;
            }

            .insertr-form-input:focus,
            .insertr-form-textarea:focus {
                outline: none;
                border-color: #007cba;
                box-shadow: 0 0 0 3px rgba(0, 124, 186, 0.1);
            }

            /* Markdown Editor Styling */
            .insertr-form-textarea {
                min-height: 120px;
                resize: vertical;
                font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
            }

            .insertr-markdown-editor {
                min-height: 200px;
                font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
                font-size: 0.9rem;
                line-height: 1.5;
                background-color: #f8fafc;
            }

            /* Form Actions */
            .insertr-form-actions {
                display: flex;
                gap: 0.5rem;
                justify-content: flex-end;
                margin-top: 1rem;
                padding-top: 1rem;
                border-top: 1px solid #e5e7eb;
            }

            .insertr-btn-save {
                background: #10b981;
                color: white;
                border: none;
                padding: 0.5rem 1rem;
                border-radius: 6px;
                font-weight: 500;
                cursor: pointer;
                transition: background-color 0.2s;
                font-size: 0.875rem;
            }

            .insertr-btn-save:hover {
                background: #059669;
            }

            .insertr-btn-cancel {
                background: #6b7280;
                color: white;
                border: none;
                padding: 0.5rem 1rem;
                border-radius: 6px;
                font-weight: 500;
                cursor: pointer;
                transition: background-color 0.2s;
                font-size: 0.875rem;
            }

            .insertr-btn-cancel:hover {
                background: #4b5563;
            }

            .insertr-btn-history {
                background: #6f42c1;
                color: white;
                border: none;
                padding: 0.5rem 1rem;
                border-radius: 6px;
                font-weight: 500;
                cursor: pointer;
                transition: background-color 0.2s;
                font-size: 0.875rem;
            }

            .insertr-btn-history:hover {
                background: #5a359a;
            }

            .insertr-form-help {
                font-size: 0.75rem;
                color: #6b7280;
                margin-top: 0.25rem;
            }

            /* Live Preview Styles */
            .insertr-preview-active {
                position: relative;
                background: rgba(0, 124, 186, 0.05) !important;
                outline: 2px solid #007cba !important;
                outline-offset: 2px;
                transition: all 0.3s ease;
            }

            .insertr-preview-active::after {
                content: "Preview";
                position: absolute;
                top: -25px;
                left: 0;
                background: #007cba;
                color: white;
                padding: 2px 8px;
                border-radius: 3px;
                font-size: 0.75rem;
                font-weight: 500;
                z-index: 10001;
                white-space: nowrap;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }

            /* Responsive Design */
            @media (max-width: 768px) {
                .insertr-edit-form {
                    min-width: 90vw;
                    max-width: 90vw;
                }
                
                .insertr-preview-active::after {
                    top: -20px;
                    font-size: 0.7rem;
                    padding: 1px 6px;
                }
            }

            /* Version History Modal Styles */
            .insertr-version-modal {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                z-index: 10001;
            }

            .insertr-version-backdrop {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }

            .insertr-version-content-modal {
                background: white;
                border-radius: 8px;
                max-width: 600px;
                width: 100%;
                max-height: 80vh;
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
                display: flex;
                flex-direction: column;
            }

            .insertr-version-header {
                padding: 20px 20px 0;
                border-bottom: 1px solid #eee;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-shrink: 0;
            }

            .insertr-version-header h3 {
                margin: 0 0 20px;
                color: #333;
                font-size: 18px;
            }

            .insertr-btn-close {
                background: none;
                border: none;
                font-size: 24px;
                cursor: pointer;
                color: #666;
                padding: 0;
                width: 30px;
                height: 30px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .insertr-btn-close:hover {
                color: #333;
            }

            .insertr-version-list {
                overflow-y: auto;
                padding: 20px;
                flex: 1;
            }

            .insertr-version-item {
                border: 1px solid #e1e5e9;
                border-radius: 6px;
                padding: 16px;
                margin-bottom: 12px;
                background: #f8f9fa;
            }

            .insertr-version-meta {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-bottom: 8px;
                font-size: 13px;
            }

            .insertr-version-label {
                font-weight: 600;
                color: #0969da;
            }

            .insertr-version-date {
                color: #656d76;
            }

            .insertr-version-user {
                color: #656d76;
            }

            .insertr-version-content {
                margin-bottom: 12px;
                padding: 8px;
                background: white;
                border-radius: 4px;
                font-family: monospace;
                font-size: 14px;
                color: #24292f;
                white-space: pre-wrap;
            }

            .insertr-version-actions {
                display: flex;
                gap: 8px;
            }

            .insertr-btn-restore {
                background: #0969da;
                color: white;
                border: none;
                padding: 6px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;
                font-weight: 500;
            }

            .insertr-btn-restore:hover {
                background: #0860ca;
            }

            .insertr-btn-view-diff {
                background: #f6f8fa;
                color: #24292f;
                border: 1px solid #d1d9e0;
                padding: 6px 12px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;
                font-weight: 500;
            }

            .insertr-btn-view-diff:hover {
                background: #f3f4f6;
            }

            .insertr-version-empty {
                text-align: center;
                color: #656d76;
                font-style: italic;
                padding: 40px 20px;
            }
        `;

        const styleSheet = document.createElement('style');
        styleSheet.type = 'text/css';
        styleSheet.innerHTML = styles;
        document.head.appendChild(styleSheet);
    }
}