{% extends "base.html" %}
{% from "_form_helpers.html" import render_field %}

{% block content %}
<div class="container">
    {% include "_flash_messages.html" %}

    <h1 class="mt-4 mb-3">Import FHIR Implementation Guides</h1>
    <div class="row">
        <div class="col-md-12">
            <p class="lead">Import new FHIR Implementation Guides to the system via file or URL.</p>
        </div>
    </div>

    <div class="row">
        <div class="col-md-6">
            <h2>Import a New IG</h2>
            <form id="manual-import-ig-form" method="POST" action="{{ url_for('manual_import_ig') }}" enctype="multipart/form-data">
                {{ form.hidden_tag() }}
                <div class="mb-3">
                    {{ render_field(form.import_mode, class="form-select") }}
                </div>
                <div id="file-field" class="{% if form.import_mode.data != 'file' %}d-none{% endif %}">
                    <div class="mb-3">
                        <label for="tgz_file" class="form-label">IG Package File (.tgz)</label>
                        <div class="input-group">
                            <input type="file" name="tgz_file" id="tgz_file" accept=".tgz" class="form-control custom-file-input">
                            <span id="file-label" class="custom-file-label">No file selected</span>
                        </div>
                        {% if form.tgz_file.errors %}
                            <div class="form-error">
                                {% for error in form.tgz_file.errors %}
                                    <p>{{ error }}</p>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                </div>
                <div id="url-field" class="{% if form.import_mode.data != 'url' %}d-none{% endif %}">
                    <div class="mb-3">
                        {{ render_field(form.tgz_url, class="form-control url-input") }}
                    </div>
                </div>
                <div class="mb-3">
                    {{ render_field(form.dependency_mode, class="form-select") }}
                </div>
                <div class="form-check mb-3">
                    {{ form.resolve_dependencies(type="checkbox", class="form-check-input") }}
                    <label class="form-check-label" for="resolve_dependencies">Resolve Dependencies</label>
                    {% if form.resolve_dependencies.errors %}
                        <div class="form-error">
                            {% for error in form.resolve_dependencies.errors %}
                                <p>{{ error }}</p>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
                <div class="d-grid gap-2 d-sm-flex mt-3">
                    {{ form.submit(class="btn btn-success", id="submit-btn") }}
                    <a href="{{ url_for('index') }}" class="btn btn-secondary">Back</a>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    .form-error {
        color: #dc3545;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }
    .custom-file-input {
        width: 100%;
        padding: 0.375rem 0.75rem;
        font-size: 1rem;
        line-height: 1.5;
        color: #495057;
        background-color: #fff;
        border: 1px solid #ced4da;
        border-radius: 0.25rem;
        cursor: pointer;
    }
    .custom-file-input::-webkit-file-upload-button {
        display: none;
    }
    .custom-file-input::before {
        content: 'Choose File';
        display: inline-block;
        background: #007bff;
        color: #fff;
        padding: 0.375rem 0.75rem;
        border-radius: 0.25rem;
        margin-right: 0.5rem;
    }
    .custom-file-input:hover::before {
        background: #0056b3;
    }
    .custom-file-label {
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
        max-width: 60%;
    }
    #file-field, #url-field {
        display: none;
    }
    #file-field:not(.d-none), #url-field:not(.d-none) {
        display: block;
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.debug('DOMContentLoaded fired for manual_import_ig.html');

    const importForm = document.getElementById('manual-import-ig-form');
    const importModeSelect = document.querySelector('#import_mode');
    const fileField = document.querySelector('#file-field');
    const urlField = document.querySelector('#url-field');
    const fileInput = document.querySelector('#tgz_file');
    const fileLabel = document.querySelector('#file-label');
    const urlInput = document.querySelector('#tgz_url');

    // Debug DOM elements
    console.debug('importForm:', !!importForm);
    console.debug('importModeSelect:', !!importModeSelect);
    console.debug('fileField:', !!fileField);
    console.debug('urlField:', !!urlField);
    console.debug('fileInput:', !!fileInput);
    console.debug('fileLabel:', !!fileLabel);
    console.debug('urlInput:', !!urlInput);

    function toggleFields() {
        if (!importModeSelect || !fileField || !urlField) {
            console.error('Required elements for toggling not found');
            return;
        }
        const mode = importModeSelect.value;
        console.debug(`Toggling fields for mode: ${mode}`);
        fileField.classList.toggle('d-none', mode !== 'file');
        urlField.classList.toggle('d-none', mode !== 'url');
        console.debug(`file-field d-none: ${fileField.classList.contains('d-none')}, url-field d-none: ${urlField.classList.contains('d-none')}`);
    }

    function updateFileLabel() {
        if (fileInput && fileLabel) {
            const fileName = fileInput.files.length > 0 ? fileInput.files[0].name : 'No file selected';
            fileLabel.textContent = fileName;
            console.debug(`Updated file label to: ${fileName}`);
        } else {
            console.warn('File input or label not found');
        }
    }

    if (importModeSelect) {
        importModeSelect.addEventListener('change', function() {
            console.debug('Import mode changed to:', importModeSelect.value);
            toggleFields();
        });
        toggleFields();
    } else {
        console.error('Import mode select not found');
    }

    if (fileInput) {
        fileInput.addEventListener('change', function() {
            console.debug('File input changed');
            updateFileLabel();
        });
        updateFileLabel();
    }

    if (urlInput) {
        urlInput.addEventListener('input', function() {
            console.debug(`URL input value: ${urlInput.value}`);
        });
    }

    if (importForm) {
        importForm.addEventListener('submit', function(evt) {
            console.debug('Form submission triggered');
            if (!importForm.checkValidity()) {
                evt.preventDefault();
                console.error('Form validation failed');
                importForm.reportValidity();
            }
        });
    }
});
</script>
{% endblock %}