{% extends "layouts/base.html" %}
{% load i18n %}
{% load static %}

{% block title %}{% if document %}{{ _("Edit Document") }}{% else %}{{ _("Upload Document") }}{% endif %} - PX360{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        background: #fff;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 25px;
        margin-bottom: 20px;
    }
    .form-section-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #667eea;
    }
    .required-field::after {
        content: " *";
        color: #dc3545;
    }
    .file-upload-wrapper {
        border: 2px dashed #dee2e6;
        border-radius: 8px;
        padding: 30px;
        text-align: center;
        transition: all 0.3s;
    }
    .file-upload-wrapper:hover {
        border-color: #667eea;
        background-color: #f8f9fa;
    }
    .current-file-info {
        background: #e7f3ff;
        border-left: 4px solid #0066cc;
        padding: 15px;
        margin-bottom: 15px;
        border-radius: 4px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-4">
        {% if folder %}
        <a href="{% url 'references:folder_view' folder.id %}" class="btn btn-outline-secondary btn-sm mb-3">
            <i class="bi bi-arrow-left me-1"></i> {{ _("Back to Folder")}}
        </a>
        {% else %}
        <a href="{% url 'references:dashboard' %}" class="btn btn-outline-secondary btn-sm mb-3">
            <i class="bi bi-arrow-left me-1"></i> {{ _("Back to Dashboard")}}
        </a>
        {% endif %}
        <h2 class="mb-1">
            {% if document %}
            <i class="bi bi-pencil-square text-primary me-2"></i>{{ _("Edit Document")}}
            {% else %}
            <i class="bi bi-upload text-primary me-2"></i>{{ _("Upload Document")}}
            {% endif %}
        </h2>
        <p class="text-muted mb-0">
            {% if document %}
            {{ _("Update document information or upload a new version")}}
            {% else %}
            {{ _("Upload a new document to the reference library")}}
            {% endif %}
        </p>
    </div>

    <form method="post" enctype="multipart/form-data" id="documentForm">
        {% csrf_token %}

        <!-- Django Messages -->
        {% if messages %}
            {% for message in messages %}
                <div class="alert alert-{{ message.tags }} alert-dismissible fade show mb-4" role="alert">
                    {{ message }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            {% endfor %}
        {% endif %}

        <!-- Form Errors -->
        {% if form.non_field_errors %}
            <div class="alert alert-danger mb-4">
                <strong><i class="bi bi-exclamation-triangle me-2"></i>{% trans "Please fix the following errors:" %}</strong>
                <ul class="mb-0 mt-2">
                    {% for error in form.non_field_errors %}
                        <li>{{ error }}</li>
                    {% endfor %}
                </ul>
            </div>
        {% endif %}

        <div class="row">
            <div class="col-lg-8">
                <!-- Document File -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-file-earmark me-2"></i>{{ _("Document File")}}
                    </h5>

                    {% if document %}
                    <div class="current-file-info">
                        <h6 class="mb-2"><i class="bi bi-file-earmark-text me-2"></i>{{ _("Current File")}}</h6>
                        <ul class="mb-0 small">
                            <li><strong>{{ _("Filename:") }}</strong> {{ document.filename }}</li>
                            <li><strong>{{ _("File Size:") }}</strong> {{ document.file_size|filesizeformat }}</li>
                            <li><strong>{{ _("Version:") }}</strong> {{ document.version }}</li>
                            <li><strong>{{ _("Uploaded:") }}</strong> {{ document.created_at|date:"M d, Y H:i" }}</li>
                        </ul>
                    </div>
                    {% endif %}

                    <div class="file-upload-wrapper">
                        <i class="bi bi-cloud-upload display-4 text-muted mb-3 d-block"></i>
                        <p class="mb-3">
                            <strong>{% trans "Drag & drop your file here" %}</strong><br>
                            <span class="text-muted">{% trans "or click to browse" %}</span>
                        </p>
                        <input type="file" name="file" class="form-control{% if form.file.errors %} is-invalid{% endif %}" id="fileInput"
                               accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png"
                               {% if not document %}required{% endif %}>
                        {% if form.file.errors %}
                            <div class="invalid-feedback d-block">
                                {% for error in form.file.errors %}
                                    {{ error }}
                                {% endfor %}
                            </div>
                        {% endif %}
                        <small class="form-text text-muted">
                            {% trans "Supported formats:" %} PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, JPG, PNG<br>
                            {% trans "Maximum file size:" %} 50 MB
                        </small>
                    </div>

                    {% if document %}
                    <div class="form-check mt-3">
                        <input class="form-check-input" type="checkbox" name="new_version" id="newVersionCheck">
                        <label class="form-check-label" for="newVersionCheck">
                            {% trans "Upload as new version (increment version number)" %}
                        </label>
                    </div>
                    {% endif %}
                </div>

                <!-- Document Details -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-info-circle me-2"></i>{{ _("Document Information")}}
                    </h5>

                    <div class="mb-3">
                        <label class="form-label required-field">{% trans "Title (English)" %}</label>
                        <input type="text" name="title" class="form-control{% if form.title.errors %} is-invalid{% endif %}"
                               value="{% if form.title.value %}{{ form.title.value }}{% elif document %}{{ document.title }}{% endif %}"
                               placeholder="{% trans 'Enter document title in English' %}" required>
                        {% if form.title.errors %}
                            <div class="invalid-feedback d-block">
                                {% for error in form.title.errors %}
                                    {{ error }}
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{% trans "Title (Arabic)" %}</label>
                        <input type="text" name="title_ar" class="form-control"
                               value="{% if form.title_ar.value %}{{ form.title_ar.value }}{% elif document %}{{ document.title_ar }}{% endif %}"
                               placeholder="{% trans 'Enter document title in Arabic (optional)' %}">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{% trans "Description (English)" %}</label>
                        <textarea name="description" class="form-control" rows="4"
                                  placeholder="{% trans 'Detailed description of the document' %}">{% if form.description.value %}{{ form.description.value }}{% elif document %}{{ document.description }}{% endif %}</textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{% trans "Description (Arabic)" %}</label>
                        <textarea name="description_ar" class="form-control" rows="4"
                                  placeholder="{% trans 'Arabic description (optional)' %}">{% if form.description_ar.value %}{{ form.description_ar.value }}{% elif document %}{{ document.description_ar }}{% endif %}</textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label{% if not folder %} required-field{% endif %}">{% trans "Folder" %}</label>
                        <select name="folder" class="form-select{% if form.folder.errors %} is-invalid{% endif %}"
                                {% if not folder %}required{% endif %}>
                            <option value="">{{ _("Select folder")}}</option>
                            {% for folder_option in all_folders %}
                            <option value="{{ folder_option.id }}"
                                    {% if document and document.folder_id == folder_option.id %}selected{% endif %}
                                    {% if folder and folder.id == folder_option.id %}selected{% endif %}>
                                {{ folder_option.level_display }}{{ folder_option.name }}
                                {% if folder_option.name_ar %}/ {{ folder_option.name_ar }}{% endif %}
                            </option>
                            {% endfor %}
                        </select>
                        {% if form.folder.errors %}
                            <div class="invalid-feedback d-block">
                                {% for error in form.folder.errors %}
                                    {{ error }}
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{% trans "Tags" %}</label>
                        <input type="text" name="tags" class="form-control"
                               value="{% if form.tags.value %}{{ form.tags.value }}{% elif document %}{{ document.tags }}{% endif %}"
                               placeholder="{% trans 'Comma-separated tags (e.g., HR, Safety, 2024)' %}">
                        <small class="form-text text-muted">{{ _("Use tags to categorize and search documents easily")}}</small>
                    </div>
                </div>

                <!-- Access Control -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i class="bi bi-shield-lock me-2"></i>{{ _("Access Control")}}
                    </h5>

                    <div class="mb-3">
                        <label class="form-label">{% trans "Access Roles" %}</label>
                        {% for choice in form.access_roles %}
                        <div class="form-check">
                            {{ choice.tag }}
                            <label class="form-check-label" for="{{ choice.id_for_label }}">
                                {{ choice.choice_label }}
                            </label>
                        </div>
                        {% empty %}
                        <p class="text-muted small">{{ _("No access roles available")}}</p>
                        {% endfor %}
                        <small class="form-text text-muted">{{ _("Select roles that can access this document")}}</small>
                    </div>

                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_published" id="isPublishedCheck"
                               {% if not document or document.is_published %}checked{% endif %}>
                        <label class="form-check-label" for="isPublishedCheck">
                            {% trans "Publish this document (make it visible to others)" %}
                        </label>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Information -->
                <div class="alert alert-info">
                    <h6 class="alert-heading">
                        <i class="bi bi-info-circle me-2"></i>{{ _("Document Guidelines")}}
                    </h6>
                    <p class="mb-0 small">
                        {{ _("Upload important documents, policies, procedures, and reference materials for easy access by your team.")}}
                    </p>
                    <hr class="my-2">
                    <ul class="mb-0 mt-2 small">
                        <li>{{ _("Use descriptive titles in both languages")}}</li>
                        <li>{{ _("Add clear descriptions")}}</li>
                        <li>{{ _("Choose the right document type")}}</li>
                        <li>{{ _("Set appropriate visibility levels")}}</li>
                        <li>{{ _("Use tags for easy searching")}}</li>
                        <li>{{ _("Upload new versions when updating")}}</li>
                    </ul>
                </div>

                <!-- Current Document Info (if editing) -->
                {% if document %}
                <div class="alert alert-secondary">
                    <h6 class="alert-heading">
                        <i class="bi bi-file-earmark me-2"></i>{{ _("Current Document")}}
                    </h6>
                    <ul class="mb-0 small">
                        <li><strong>{{ _("Created:") }}</strong> {{ document.created_at|date:"M d, Y H:i" }}</li>
                        <li><strong>{{ _("Updated:") }}</strong> {{ document.updated_at|date:"M d, Y H:i" }}</li>
                        <li><strong>{{ _("Version:") }}</strong> {{ document.version }}</li>
                        <li><strong>{{ _("File Size:") }}</strong> {{ document.file_size|filesizeformat }}</li>
                    </ul>
                </div>
                {% endif %}

                <!-- Action Buttons -->
                <div class="d-grid gap-2">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="bi bi-check-circle me-2"></i>
                        {% if document %}{{ _("Update Document")}}{% else %}{{ _("Upload Document")}}{% endif %}
                    </button>
                    {% if folder %}
                    <a href="{% url 'references:folder_view' folder.id %}" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle me-2"></i>{{ _("Cancel")}}
                    </a>
                    {% else %}
                    <a href="{% url 'references:dashboard' %}" class="btn btn-outline-secondary">
                        <i class="bi bi-x-circle me-2"></i>{{ _("Cancel")}}
                    </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('documentForm');
    const fileInput = document.getElementById('fileInput');
    const fileUploadWrapper = document.querySelector('.file-upload-wrapper');

    // Drag and drop functionality
    fileUploadWrapper.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.style.borderColor = '#667eea';
        this.style.backgroundColor = '#e7f3ff';
    });

    fileUploadWrapper.addEventListener('dragleave', function(e) {
        e.preventDefault();
        this.style.borderColor = '#dee2e6';
        this.style.backgroundColor = '#fff';
    });

    fileUploadWrapper.addEventListener('drop', function(e) {
        e.preventDefault();
        this.style.borderColor = '#dee2e6';
        this.style.backgroundColor = '#fff';

        const files = e.dataTransfer.files;
        if (files.length > 0) {
            fileInput.files = files;
            updateFileName(files[0].name);
        }
    });

    // Handle file selection via click
    fileInput.addEventListener('change', function(e) {
        if (this.files.length > 0) {
            updateFileName(this.files[0].name);
        }
    });

    function updateFileName(fileName) {
        const icon = fileUploadWrapper.querySelector('i');
        const p = fileUploadWrapper.querySelector('p');

        icon.className = 'bi bi-file-earmark-check display-4 text-success mb-3 d-block';
        p.innerHTML = `<strong>${fileName}</strong><br><span class="text-muted">{% trans "File selected" %}</span>`;
    }

    // Form validation
    form.addEventListener('submit', function(e) {
        if (!form.checkValidity()) {
            e.preventDefault();
            e.stopPropagation();
        }
        form.classList.add('was-validated');
    });
});
</script>
{% endblock %}
