// js/mime-document-dossier-admin.js
const API_BASE_URL = '/est-concours/model/api/mime-document-dossier-admin.php';
let currentPage = 1;
const perPage = 10;
let totalPages = 1;
let editMode = false;
let currentDetailId = null;

// Available badges for badge display
const BADGE_COLORS = {
    primary: '#007bff',
    secondary: '#6c757d',
    success: '#28a745',
    danger: '#dc3545',
    warning: '#ffc107',
    info: '#17a2b8',
    dark: '#343a40'
};

// Load mime types on page load
document.addEventListener('DOMContentLoaded', function() {
    loadMimeTypes();
    loadStats();
    setupSearchForm();
});

function setupSearchForm() {
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        currentPage = 1;
        loadMimeTypes();
    });
}

function resetSearch() {
    document.getElementById('searchForm').reset();
    document.getElementById('searchBadge').value = '';
    currentPage = 1;
    loadMimeTypes();
}

function loadStats() {
    // Load mime types stats
    fetch(`${API_BASE_URL}?action=stats`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                const stats = result.data;
                document.getElementById('statTotal').textContent = stats.total || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));

    // Load badges count (hardcoded as 7)
    document.getElementById('statBadges').textContent = '7';
}

function loadMimeTypes() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        libelle: document.getElementById('searchLibelle')?.value || '',
        code: document.getElementById('searchCode')?.value || '',
        badge: document.getElementById('searchBadge')?.value || '',
        description: document.getElementById('searchDescription')?.value || '',
        page: currentPage,
        per_page: perPage
    };

    const params = new URLSearchParams(searchData);

    fetch(`${API_BASE_URL}?action=search&${params.toString()}`)
        .then(response => response.json())
        .then(result => {
            showLoading(false);
            if (result.success) {
                renderTable(result.data.data);
                renderPagination(result.data);
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            showLoading(false);
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function renderTable(mimeTypes) {
    const tbody = document.getElementById('tableBody');

    if (mimeTypes.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; padding: 40px; color: #666;">
                    <p style="font-size: 18px;">📭 Aucun type MIME trouvé</p>
                    <p style="font-size: 14px; margin-top: 5px;">Essayez de modifier vos critères de recherche</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = mimeTypes.map(mime => `
        <tr>
            <td>${mime.id}</td>
            <td><strong>${escapeHtml(mime.libelle)}</strong></td>
            <td><code style="background: #f4f4f4; padding: 2px 8px; border-radius: 4px; font-size: 12px;">${escapeHtml(mime.code)}</code></td>
            <td>
                <span class="badge badge-${mime.badge || 'secondary'}">
                    ${escapeHtml(mime.badge || 'default')}
                </span>
            </td>
            <td>${escapeHtml(mime.description || '-')}</td>
            <td>${formatDate(mime.created_at)}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${mime.id})" title="Voir les détails">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${mime.id})" title="Modifier">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteMimeType(${mime.id})" title="Supprimer">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function renderPagination(data) {
    const { total, page, totalPages: pages } = data;
    totalPages = pages;

    const start = (page - 1) * perPage + 1;
    const end = Math.min(page * perPage, total);
    document.getElementById('paginationInfo').textContent =
        `Affichage de ${start} à ${end} sur ${total} types MIME`;

    const pageNumbers = document.getElementById('pageNumbers');
    let html = '';
    for (let i = 1; i <= pages; i++) {
        html += `<button onclick="goToPage(${i})" ${i === page ? 'class="active"' : ''}>${i}</button>`;
    }
    pageNumbers.innerHTML = html;

    document.getElementById('prevBtn').disabled = page <= 1;
    document.getElementById('nextBtn').disabled = page >= pages;
}

function changePage(direction) {
    if (direction === 'prev' && currentPage > 1) {
        currentPage--;
    } else if (direction === 'next' && currentPage < totalPages) {
        currentPage++;
    }
    loadMimeTypes();
}

function goToPage(page) {
    currentPage = page;
    loadMimeTypes();
}

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Type MIME';
    document.getElementById('mimeForm').reset();
    document.getElementById('mimeId').value = '';
    document.getElementById('badge').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Type MIME';
    document.getElementById('mimeId').value = id;

    // Close detail modal if open
    if (document.getElementById('detailModal').classList.contains('active')) {
        closeDetailModal();
    }

    // Show loading state
    document.querySelector('.modal-overlay').classList.add('active');
    document.getElementById('libelle').value = 'Chargement...';
    document.getElementById('libelle').disabled = true;
    document.getElementById('code').value = 'Chargement...';
    document.getElementById('code').disabled = true;
    document.getElementById('badge').disabled = true;
    document.getElementById('description').value = 'Chargement...';
    document.getElementById('description').disabled = true;

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            // Enable fields
            document.getElementById('libelle').disabled = false;
            document.getElementById('code').disabled = false;
            document.getElementById('badge').disabled = false;
            document.getElementById('description').disabled = false;

            if (result.success) {
                const mime = result.data;
                document.getElementById('libelle').value = mime.libelle;
                document.getElementById('code').value = mime.code;
                document.getElementById('badge').value = mime.badge || '';
                document.getElementById('description').value = mime.description || '';
            } else {
                showToast('Erreur: ' + result.message, 'error');
                closeModal();
            }
        })
        .catch(error => {
            document.getElementById('libelle').disabled = false;
            document.getElementById('code').disabled = false;
            document.getElementById('badge').disabled = false;
            document.getElementById('description').disabled = false;
            showToast('Erreur de connexion au serveur', 'error');
            closeModal();
            console.error('Error:', error);
        });
}

function viewDetail(id) {
    currentDetailId = id;

    // Show modal with loading state
    document.getElementById('detailModal').classList.add('active');
    document.getElementById('detailContent').innerHTML = `
        <div class="loading active">
            <div class="spinner"></div>
            <p style="margin-top: 10px;">Chargement des détails...</p>
        </div>
    `;

    // Hide edit button initially
    document.getElementById('editFromDetailBtn').style.display = 'none';

    fetch(`${API_BASE_URL}?action=get&id=${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                renderDetail(result.data);
            } else {
                document.getElementById('detailContent').innerHTML = `
                    <div class="error-state">
                        <i class="fas fa-exclamation-circle"></i>
                        <p>Erreur: ${result.message}</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('detailContent').innerHTML = `
                <div class="error-state">
                    <i class="fas fa-exclamation-circle"></i>
                    <p>Erreur de connexion au serveur</p>
                </div>
            `;
            console.error('Error:', error);
        });
}

function renderDetail(mime) {
    const badgeClass = mime.badge || 'secondary';
    const badgeStyle = BADGE_COLORS[mime.badge] || BADGE_COLORS.secondary;

    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <!-- Header with icon -->
            <div class="detail-header">
                <div class="detail-avatar" style="background: ${badgeStyle}33;">
                    <i class="fas fa-file" style="color: ${badgeStyle};"></i>
                </div>
                <div class="detail-title">
                    <h2>${escapeHtml(mime.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">
                            <i class="fas fa-tag"></i> ${escapeHtml(mime.code)}
                        </span>
                        <span class="badge badge-${badgeClass}">
                            <i class="fas fa-palette"></i> ${escapeHtml(mime.badge || 'default')}
                        </span>
                        <span class="meta-text">
                            <i class="fas fa-calendar-alt"></i> 
                            Créé le ${formatDate(mime.created_at)}
                        </span>
                        ${mime.updated_at ? `
                            <span class="meta-text">
                                <i class="fas fa-edit"></i> 
                                Mis à jour le ${formatDate(mime.updated_at)}
                            </span>
                        ` : ''}
                    </div>
                </div>
            </div>
            
            <!-- Information Grid -->
            <h3><i class="fas fa-info-circle"></i> Informations du Type MIME</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label"><i class="fas fa-hashtag"></i> ID</span>
                    <span class="value">${mime.id}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-code"></i> Code MIME</span>
                    <span class="value">
                        <code style="background: #f4f4f4; padding: 2px 10px; border-radius: 4px; font-size: 13px;">${escapeHtml(mime.code)}</code>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-palette"></i> Badge</span>
                    <span class="value">
                        <span class="badge badge-${badgeClass}" style="background: ${badgeStyle}; color: #fff;">
                            ${escapeHtml(mime.badge || 'default')}
                        </span>
                    </span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-align-left"></i> Libellé</span>
                    <span class="value">${escapeHtml(mime.libelle)}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-file-alt"></i> Description</span>
                    <span class="value ${!mime.description ? 'empty' : ''}">
                        ${mime.description ? escapeHtml(mime.description) : 'Aucune description'}
                    </span>
                </div>
            </div>
            
            <!-- Metadata -->
            <div class="detail-metadata">
                <h4><i class="fas fa-clock"></i> Métadonnées</h4>
                <div class="metadata-grid">
                    <div class="meta-item">
                        <span class="meta-label">Date de création:</span>
                        <span class="meta-value">${formatDate(mime.created_at)}</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">Dernière mise à jour:</span>
                        <span class="meta-value">${mime.updated_at ? formatDate(mime.updated_at) : 'Jamais'}</span>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Show the edit button
    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';
}

function editFromDetail() {
    if (currentDetailId) {
        closeDetailModal();
        // Small delay to allow modal to close
        setTimeout(() => {
            openEditModal(currentDetailId);
        }, 300);
    }
}

function closeDetailModal() {
    document.getElementById('detailModal').classList.remove('active');
    currentDetailId = null;
}

function saveMimeType() {
    // Validation
    const libelle = document.getElementById('libelle').value.trim();
    const code = document.getElementById('code').value.trim();
    const badge = document.getElementById('badge').value;
    const description = document.getElementById('description').value.trim();

    if (!libelle) {
        showToast('Veuillez saisir le libellé du type MIME', 'warning');
        document.getElementById('libelle').focus();
        return;
    }

    if (!code) {
        showToast('Veuillez saisir le code MIME', 'warning');
        document.getElementById('code').focus();
        return;
    }

    if (!badge) {
        showToast('Veuillez sélectionner un badge', 'warning');
        document.getElementById('badge').focus();
        return;
    }

    // Validate MIME code format (contains '/')
    if (!code.includes('/')) {
        showToast('Le code MIME doit être au format "type/sous-type" (ex: application/pdf, image/jpeg)', 'warning');
        return;
    }

    const id = document.getElementById('mimeId').value;
    const data = {
        libelle: libelle,
        code: code,
        badge: badge,
        description: description || null
    };

    const url = id ? `${API_BASE_URL}?action=update&id=${id}` : API_BASE_URL;
    const method = id ? 'PUT' : 'POST';

    // Show loading state on button
    const saveBtn = document.querySelector('.modal-content .btn-primary');
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Enregistrement...';
    saveBtn.disabled = true;

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response => response.json())
        .then(result => {
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;

            if (result.success) {
                showToast(result.message, 'success');
                closeModal();
                loadMimeTypes();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function deleteMimeType(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce type MIME ?\n\nCette action est irréversible.')) return;

    // Show loading state on button
    const btn = document.querySelector(`button[onclick="deleteMimeType(${id})"]`);
    if (btn) {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
        btn.disabled = true;
    }

    fetch(`${API_BASE_URL}?action=delete&id=${id}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(result => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }

            if (result.success) {
                showToast(result.message, 'success');
                loadMimeTypes();
                loadStats();
            } else {
                showToast('Erreur: ' + result.message, 'error');
            }
        })
        .catch(error => {
            if (btn) {
                btn.innerHTML = '<i class="fas fa-trash"></i>';
                btn.disabled = false;
            }
            showToast('Erreur de connexion au serveur', 'error');
            console.error('Error:', error);
        });
}

function exportMimeTypes() {
    window.location.href = `${API_BASE_URL}?action=export`;
}

function closeModal() {
    document.querySelector('.modal-overlay').classList.remove('active');
}

function showLoading(show) {
    const loading = document.querySelector('.loading');
    if (loading) {
        if (show) {
            loading.classList.add('active');
        } else {
            loading.classList.remove('active');
        }
    }
}

function showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerHTML = `
        <span class="toast-icon">${getToastIcon(type)}</span>
        <span class="toast-message">${message}</span>
        <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    container.appendChild(toast);

    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            toast.style.transition = 'all 0.3s ease';
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 300);
        }
    }, 4000);
}

function getToastIcon(type) {
    const icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };
    return icons[type] || 'ℹ️';
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Close modal on overlay click
document.querySelectorAll('.modal-overlay').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            if (this.id === 'detailModal') {
                closeDetailModal();
            } else {
                closeModal();
            }
        }
    });
});

// Close modal on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        if (document.getElementById('detailModal').classList.contains('active')) {
            closeDetailModal();
        } else if (document.querySelector('.modal-overlay.active')) {
            closeModal();
        }
    }
});