{% extends "base-layout.html.twig" %}

{% block title %}Admin - Member Import{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard">
                            <i class="fas fa-tachometer-alt"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/member-import">
                            <i class="fas fa-users"></i> Member Import
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/site-config">
                            <i class="fas fa-cog"></i> Site Configuration
                        </a>
                    </li>
                </ul>
            </div>
        </div>

        <!-- Main content -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Member Import</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="downloadTemplate()">
                            <i class="fas fa-download"></i> Download Excel Template
                        </button>
                    </div>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Members</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.totalUsers }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-users fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Imported Members</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ importedCount }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-file-import fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Welcome Pending</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ welcomePending }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-hand-wave fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Last Import</div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ lastImportDate }}</div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-calendar fa-2x text-gray-300"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Import Form -->
            <div class="row">
                <div class="col-lg-8">
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Upload Member List</h6>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-info">
                                <h6><i class="fas fa-info-circle"></i> Import Instructions</h6>
                                <ul class="mb-0">
                                    <li>Download the Excel template using the button above</li>
                                    <li>Fill in member information (max 1000 members per import)</li>
                                    <li>Ensure all email addresses are unique</li>
                                    <li>Use strong initial passwords</li>
                                    <li>Members will receive welcome emails with login instructions</li>
                                </ul>
                            </div>

                            <form id="importForm" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="excelFile" class="form-label">Excel File (.xlsx)</label>
                                    <input type="file" class="form-control" id="excelFile" name="excelFile" accept=".xlsx,.xls" required>
                                    <div class="form-text">Select an Excel file with member data</div>
                                </div>

                                <div class="mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="sendWelcomeEmails">
                                        <label class="form-check-label" for="sendWelcomeEmails">
                                            Send welcome emails to imported members
                                        </label>
                                    </div>
                                </div>

                                <button type="submit" class="btn btn-primary" id="importBtn">
                                    <i class="fas fa-upload"></i> Import Members
                                </button>
                            </form>

                            <!-- Progress Bar -->
                            <div id="importProgress" class="mt-3" style="display: none;">
                                <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                                </div>
                                <div class="text-center mt-2">
                                    <small id="progressText">Processing...</small>
                                </div>
                            </div>

                            <!-- Results -->
                            <div id="importResults" class="mt-3" style="display: none;">
                                <!-- Results will be populated here -->
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Recent Imports</h6>
                        </div>
                        <div class="card-body">
                            {% if recentImports|length > 0 %}
                                {% for import in recentImports %}
                                    <div class="d-flex align-items-center mb-3">
                                        <div class="flex-shrink-0">
                                            <i class="fas fa-file-excel text-success"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h6 class="mb-0">{{ import.memberCount }} members</h6>
                                            <small class="text-muted">{{ import.importDate|date('M j, Y g:i A') }}</small>
                                        </div>
                                    </div>
                                {% endfor %}
                            {% else %}
                                <p class="text-muted">No recent imports</p>
                            {% endif %}
                        </div>
                    </div>

                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Welcome Sequence</h6>
                        </div>
                        <div class="card-body">
                            <p>New members go through a welcome sequence:</p>
                            <ol>
                                <li>Email with login credentials</li>
                                <li>Profile completion prompt</li>
                                <li>Community tour</li>
                                <li>First item addition guidance</li>
                                <li>Community introduction</li>
                            </ol>
                            <a href="/admin/welcome-config" class="btn btn-sm btn-outline-primary">
                                Configure Welcome Sequence
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Download Excel template
function downloadTemplate() {
    window.location.href = '/api/admin/member-import/template';
}

// Handle form submission
document.getElementById('importForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const fileInput = document.getElementById('excelFile');
    const sendEmails = document.getElementById('sendWelcomeEmails').checked;
    const progressDiv = document.getElementById('importProgress');
    const resultsDiv = document.getElementById('importResults');
    const importBtn = document.getElementById('importBtn');
    
    if (!fileInput.files[0]) {
        alert('Please select an Excel file');
        return;
    }
    
    // Show progress
    progressDiv.style.display = 'block';
    resultsDiv.style.display = 'none';
    importBtn.disabled = true;
    importBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    
    const formData = new FormData();
    formData.append('excelFile', fileInput.files[0]);
    formData.append('sendWelcomeEmails', sendEmails);
    
    try {
        const response = await fetch('/api/admin/member-import', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        displayImportResults(result);
        
        if (result.success) {
            fileInput.value = '';
            document.getElementById('sendWelcomeEmails').checked = false;
        }
    } catch (error) {
        console.error('Import error:', error);
        displayImportResults({
            success: false,
            errors: ['Network error occurred during import']
        });
    } finally {
        progressDiv.style.display = 'none';
        importBtn.disabled = false;
        importBtn.innerHTML = '<i class="fas fa-upload"></i> Import Members';
    }
});

function displayImportResults(result) {
    const resultsDiv = document.getElementById('importResults');
    let html = '';
    
    if (result.success) {
        html += `<div class="alert alert-success">
            <h6><i class="fas fa-check-circle"></i> Import Successful</h6>
            <p>Successfully imported ${result.imported} members.</p>
        </div>`;
    }
    
    if (result.duplicates && result.duplicates.length > 0) {
        html += `<div class="alert alert-warning">
            <h6><i class="fas fa-exclamation-triangle"></i> Duplicate Emails (${result.duplicates.length})</h6>
            <ul class="mb-0">
                ${result.duplicates.map(dup => `<li>${dup}</li>`).join('')}
            </ul>
        </div>`;
    }
    
    if (result.errors && result.errors.length > 0) {
        html += `<div class="alert alert-danger">
            <h6><i class="fas fa-exclamation-circle"></i> Errors (${result.errors.length})</h6>
            <ul class="mb-0">
                ${result.errors.map(error => `<li>${error}</li>`).join('')}
            </ul>
        </div>`;
    }
    
    resultsDiv.innerHTML = html;
    resultsDiv.style.display = 'block';
}
</script>

<style>
.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
    padding: 48px 0 0;
    box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}

.sidebar .nav-link {
    font-weight: 500;
    color: #333;
}

.sidebar .nav-link.active {
    color: #007bff;
}

.border-left-primary {
    border-left: 0.25rem solid #4e73df !important;
}

.border-left-success {
    border-left: 0.25rem solid #1cc88a !important;
}

.border-left-info {
    border-left: 0.25rem solid #36b9cc !important;
}

.border-left-warning {
    border-left: 0.25rem solid #f6c23e !important;
}

.text-xs {
    font-size: 0.7rem;
}

.font-weight-bold {
    font-weight: 700 !important;
}

.text-uppercase {
    text-transform: uppercase !important;
}

.text-gray-800 {
    color: #5a5c69 !important;
}

.text-gray-300 {
    color: #dddfeb !important;
}
</style>
{% endblock %}