{% extends "admin/index.html" %}

{% block admin_content %}
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">Import/Export All Data</h5>
    </div>
    <div class="card-body">
        <p>
            This section allows you to export all your data (foods, meals, plans, etc.) into a single JSON file. 
            You can also import this data back, which will overwrite any existing data. 
            This is useful for backups or migrating to a new instance.
        </p>
        
        <div class="mb-3">
            <a href="/export/all" class="btn btn-primary" download="meal_planner_backup.json">
                <i class="bi bi-download"></i> Export All Data
            </a>
        </div>

        <hr>

        <h5>Import Data</h5>
        <form id="import-form" action="/import/all" method="post" enctype="multipart/form-data">
            <div class="mb-3">
                <label for="import-file" class="form-label">Select JSON file to import</label>
                <input class="form-control" type="file" id="import-file" name="file" accept=".json">
            </div>
            <button type="submit" class="btn btn-success">
                <i class="bi bi-upload"></i> Import and Overwrite
            </button>
        </form>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Food Import</h5>
            </div>
            <div class="card-body">
                <form action="/foods/upload" method="post" enctype="multipart/form-data" class="csv-upload-form">
                    <div class="mb-3">
                        <label class="form-label">CSV File</label>
                        <input type="file" class="form-control" name="file" accept=".csv" required>
                    </div>
                    <button type="submit" class="btn btn-secondary">Upload Foods CSV</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Meal Import</h5>
            </div>
            <div class="card-body">
                <form action="/meals/upload" method="post" enctype="multipart/form-data" class="csv-upload-form">
                    <div class="mb-3">
                        <label class="form-label">CSV File</label>
                        <input type="file" class="form-control" name="file" accept=".csv" required>
                    </div>
                    <button type="submit" class="btn btn-secondary">Upload Meals CSV</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Template Import</h5>
            </div>
            <div class="card-body">
                <form action="/templates/upload" method="post" enctype="multipart/form-data" class="csv-upload-form">
                    <div class="mb-3">
                        <label class="form-label">CSV File</label>
                        <input type="file" class="form-control" name="file" accept=".csv" required>
                    </div>
                    <button type="submit" class="btn btn-secondary">Upload Templates CSV</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="mt-4" id="upload-results" style="display: none;">
    <div class="alert">
        <strong>Upload Results:</strong>
        <p>Created: <span id="created-count"></span></p>
        <p>Updated: <span id="updated-count"></span></p>
        <div id="error-list" class="mt-2 text-danger"></div>
    </div>
</div>

<script>
document.querySelectorAll('.csv-upload-form').forEach(form => {
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const submitBtn = form.querySelector('button[type="submit"]');
        const resultsDiv = document.getElementById('upload-results');
        const alertDiv = resultsDiv.querySelector('.alert');
        
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Uploading...';
        
        try {
            const formData = new FormData(form);
            const response = await fetch(form.action, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            
            const results = await response.json();
            resultsDiv.style.display = 'block';
            
            if (results.status === 'error') {
                alertDiv.className = 'alert alert-danger';
                document.getElementById('created-count').textContent = 'N/A';
                document.getElementById('updated-count').textContent = 'N/A';
                document.getElementById('error-list').innerHTML = `<strong>Error:</strong> ${results.message}`;
            } else {
                alertDiv.className = 'alert alert-success';
                document.getElementById('created-count').textContent = results.created || 0;
                document.getElementById('updated-count').textContent = results.updated || 0;

                if (results.errors?.length > 0) {
                    document.getElementById('error-list').innerHTML =
                        `<strong>Errors (${results.errors.length}):</strong><br>` + results.errors.join('<br>');
                } else {
                    document.getElementById('error-list').innerHTML = '';
                }
            }

        } catch (error) {
            resultsDiv.style.display = 'block';
            alertDiv.className = 'alert alert-danger';
            document.getElementById('created-count').textContent = 'N/A';
            document.getElementById('updated-count').textContent = 'N/A';
            document.getElementById('error-list').innerHTML =
                `<strong>Upload Failed:</strong> ${error.message}`;
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = 'Upload CSV';
        }
    });
});
</script>
{% endblock %}