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

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

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

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

function loadStats() {
    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;
                document.getElementById('statActif').textContent = stats.total || 0;
            }
        })
        .catch(error => console.error('Error loading stats:', error));
}

function loadTypes() {
    showLoading(true);

    const searchData = {
        id: document.getElementById('searchId')?.value || '',
        libelle: document.getElementById('searchLibelle')?.value || '',
        code: document.getElementById('searchCode')?.value || '',
        description: document.getElementById('searchDescription')?.value || '',
        template_document: document.getElementById('searchTemplate')?.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(types) {
    const tbody = document.getElementById('tableBody');

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

    tbody.innerHTML = types.map(type => `
        <tr>
            <td>${type.id}</td>
            <td><strong>${escapeHtml(type.libelle)}</strong></td>
            <td><span class="badge badge-info">${escapeHtml(type.code)}</span></td>
            <td>${escapeHtml(type.description || '-')}</td>
            <td>${type.template_document ? `<span class="badge badge-secondary">${escapeHtml(type.template_document)}</span>` : '-'}</td>
            <td>${formatDate(type.created_at)}</td>
            <td>${type.updated_at ? formatDate(type.updated_at) : '-'}</td>
            <td>
                <button class="btn btn-info btn-sm" onclick="viewDetail(${type.id})" title="Voir les détails">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-warning btn-sm" onclick="openEditModal(${type.id})" title="Modifier">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-danger btn-sm" onclick="deleteType(${type.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`;

    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++;
    }
    loadTypes();
}

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

function openCreateModal() {
    editMode = false;
    document.getElementById('modalTitle').textContent = 'Nouveau Type de Document';
    document.getElementById('typeDocumentForm').reset();
    document.getElementById('typeDocumentId').value = '';
    document.querySelector('.modal-overlay').classList.add('active');
}

function openEditModal(id) {
    editMode = true;
    document.getElementById('modalTitle').textContent = 'Modifier Type de Document';
    document.getElementById('typeDocumentId').value = id;

    if (document.getElementById('detailModal').classList.contains('active')) {
        closeDetailModal();
    }

    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('description').value = 'Chargement...';
    document.getElementById('description').disabled = true;
    document.getElementById('template_document').value = 'Chargement...';
    document.getElementById('template_document').disabled = true;

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

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

function viewDetail(id) {
    currentDetailId = id;

    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>
    `;

    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(type) {
    document.getElementById('detailContent').innerHTML = `
        <div class="detail-section">
            <div class="detail-header">
                <div class="detail-avatar">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="detail-title">
                    <h2>${escapeHtml(type.libelle)}</h2>
                    <div class="detail-meta">
                        <span class="badge badge-info">
                            <i class="fas fa-tag"></i> ${escapeHtml(type.code)}
                        </span>
                        <span class="meta-text">
                            <i class="fas fa-calendar-alt"></i> 
                            Créé le ${formatDate(type.created_at)}
                        </span>
                        ${type.updated_at ? `
                            <span class="meta-text">
                                <i class="fas fa-edit"></i> 
                                Mis à jour le ${formatDate(type.updated_at)}
                            </span>
                        ` : ''}
                    </div>
                </div>
            </div>
            
            <h3><i class="fas fa-info-circle"></i> Informations du Type de Document</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="label"><i class="fas fa-hashtag"></i> ID</span>
                    <span class="value">${type.id}</span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-tag"></i> Code</span>
                    <span class="value">
                        <span class="badge badge-info">${escapeHtml(type.code)}</span>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="label"><i class="fas fa-file-pdf"></i> Template</span>
                    <span class="value">
                        ${type.template_document ?
        `<span class="badge badge-secondary">${escapeHtml(type.template_document)}</span>` :
        '<span class="empty">Aucun template</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(type.libelle)}</span>
                </div>
                <div class="detail-item full-width">
                    <span class="label"><i class="fas fa-file-alt"></i> Description</span>
                    <span class="value ${!type.description ? 'empty' : ''}">
                        ${type.description ? escapeHtml(type.description) : 'Aucune description'}
                    </span>
                </div>
            </div>
            
            <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(type.created_at)}</span>
                    </div>
                    <div class="meta-item">
                        <span class="meta-label">Dernière mise à jour:</span>
                        <span class="meta-value">${type.updated_at ? formatDate(type.updated_at) : 'Jamais'}</span>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.getElementById('editFromDetailBtn').style.display = 'inline-flex';
}

function editFromDetail() {
    if (currentDetailId) {
        closeDetailModal();
        setTimeout(() => {
            openEditModal(currentDetailId);
        }, 300);
    }
}

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

function saveTypeDocument() {
    const libelle = document.getElementById('libelle').value.trim();
    const code = document.getElementById('code').value.trim();
    const description = document.getElementById('description').value.trim();
    const template_document = document.getElementById('template_document').value.trim();

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

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

    if (!/^[A-Z_]+$/.test(code)) {
        showToast('Le code doit être en majuscules et sans espaces (ex: STG, CNG, MSN, ATT)', 'warning');
        return;
    }

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

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

    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();
                loadTypes();
                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 deleteType(id) {
    if (!confirm('Êtes-vous sûr de vouloir supprimer ce type de document ?\n\nCette action est irréversible.')) return;

    const btn = document.querySelector(`button[onclick="deleteType(${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');
                loadTypes();
                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 exportTypes() {
    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();
        }
    }
});
