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

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

{% block extra_css %}
<style>
    :root {
        --hh-navy: #005696;
        --hh-blue: #007bbd;
        --hh-light: #eef6fb;
        --hh-slate: #64748b;
    }

    .page-header-gradient {
        background: linear-gradient(135deg, var(--hh-navy) 0%, #0069a8 50%, var(--hh-blue) 100%);
        color: white;
        padding: 1.5rem 2rem;
        border-radius: 1rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
    }

    .form-section {
        background: #fff;
        border: 2px solid #e2e8f0;
        border-radius: 1rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        transition: all 0.3s ease;
    }
    .form-section:hover {
        border-color: #005696;
        box-shadow: 0 4px 12px rgba(0, 86, 150, 0.1);
    }

    .form-section-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 1.25rem;
        padding-bottom: 0.75rem;
        border-bottom: 2px solid #005696;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .required-field::after {
        content: " *";
        color: #ef4444;
    }

    .form-control-px360 {
        width: 100%;
        padding: 0.625rem 0.875rem;
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        transition: all 0.2s;
    }
    .form-control-px360:focus {
        outline: none;
        border-color: #005696;
        box-shadow: 0 0 0 3px rgba(0, 86, 150, 0.1);
    }

    .form-select-px360 {
        width: 100%;
        padding: 0.625rem 0.875rem;
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        transition: all 0.2s;
        background: white;
    }
    .form-select-px360:focus {
        outline: none;
        border-color: #005696;
        box-shadow: 0 0 0 3px rgba(0, 86, 150, 0.1);
    }

    .file-upload-wrapper {
        border: 2px dashed #cbd5e1;
        border-radius: 0.75rem;
        padding: 2rem;
        text-align: center;
        transition: all 0.3s;
        background: #f8fafc;
    }
    .file-upload-wrapper:hover {
        border-color: #005696;
        background-color: #eef6fb;
    }

    .current-file-info {
        background: #e7f3ff;
        border-left: 4px solid #005696;
        padding: 1rem;
        margin-bottom: 1rem;
        border-radius: 0.5rem;
    }

    .btn-transition {
        transition: all 0.2s ease-in-out;
    }

    .alert-info-px360 {
        background: #e7f3ff;
        border: 1px solid #005696;
        border-radius: 0.75rem;
        padding: 1rem;
    }

    .alert-secondary-px360 {
        background: #f1f5f9;
        border: 1px solid #cbd5e1;
        border-radius: 0.75rem;
        padding: 1rem;
    }

    .hh-btn-primary {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.5rem;
        background: #005696;
        color: white;
        border-radius: 0.75rem;
        font-weight: 600;
        transition: all 0.2s ease;
        border: none;
        cursor: pointer;
    }
    .hh-btn-primary:hover {
        background: #007bbd;
    }

    .hh-btn-secondary {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.5rem;
        background: white;
        color: #64748b;
        border: 2px solid #e2e8f0;
        border-radius: 0.75rem;
        font-weight: 600;
        transition: all 0.2s ease;
    }
    .hh-btn-secondary:hover {
        background: #f1f5f9;
        border-color: #005696;
    }
</style>
{% endblock %}

{% block content %}
<div class="px-6 py-4">
    <!-- Page Header -->
    <div class="page-header-gradient mb-6">
        <div class="flex items-center gap-3">
            <div class="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
                {% if document %}
                <i data-lucide="file-edit" class="w-6 h-6 text-white"></i>
                {% else %}
                <i data-lucide="upload-cloud" class="w-6 h-6 text-white"></i>
                {% endif %}
            </div>
            <div>
                <h2 class="text-2xl font-bold">
                    {% if document %}{{ _("Edit Document")}}{% else %}{{ _("Upload Document")}}{% endif %}
                </h2>
                <p class="text-blue-100 text-sm">
                    {% if document %}{{ _("Update document information")}}{% else %}{{ _("Upload a new document")}}{% endif %}
                </p>
            </div>
        </div>
    </div>

    <form method="post" enctype="multipart/form-data" id="documentForm" data-loading data-loading-text="{% trans 'Uploading...' %}">
        {% csrf_token %}

        <!-- Messages -->
        {% if messages %}
            {% for message in messages %}
                <div class="p-4 rounded-xl mb-4 border {% if message.tags == 'success' %}bg-green-50 border-green-200 text-green-800{% elif message.tags == 'error' %}bg-red-50 border-red-200 text-red-800{% else %}bg-blue-50 border-blue-200 text-blue-800{% endif %}" role="alert">
                    {{ message }}
                </div>
            {% endfor %}
        {% endif %}

        <!-- Form Errors -->
        {% if form.non_field_errors %}
            <div class="bg-red-50 border-2 border-red-200 text-red-800 p-4 rounded-xl mb-4">
                <strong class="flex items-center gap-2 mb-2"><i data-lucide="alert-triangle" class="w-5 h-5"></i>{% trans "Please fix the following errors:" %}</strong>
                <ul class="mb-0 mt-2 list-disc list-inside">
                    {% for error in form.non_field_errors %}
                        <li>{{ error }}</li>
                    {% endfor %}
                </ul>
            </div>
        {% endif %}

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div class="lg:col-span-2">
                <!-- Document File -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i data-lucide="file-up" class="w-5 h-5"></i>{{ _("Document File")}}
                    </h5>

                    {% if document %}
                    <div class="current-file-info">
                        <h6 class="mb-2 text-sm font-semibold text-navy flex items-center gap-2">
                            <i data-lucide="file-check" class="w-4 h-4"></i>{{ _("Current File")}}
                        </h6>
                        <ul class="mb-0 text-xs text-slate-600 space-y-1">
                            <li><strong>{{ _("Filename:") }}</strong> {{ document.filename }}</li>
                            <li><strong>{{ _("Size:") }}</strong> {{ document.file_size|filesizeformat }}</li>
                            <li><strong>{{ _("Version:") }}</strong> {{ document.version }}</li>
                        </ul>
                    </div>
                    {% endif %}

                    <div class="file-upload-wrapper">
                        <i data-lucide="cloud-upload" class="w-16 h-16 mx-auto mb-3 text-slate-400"></i>
                        <p class="mb-3">
                            <strong class="text-gray-700">{% trans "Drag & drop your file here" %}</strong><br>
                            <span class="text-slate-500 text-sm">{% trans "or click to browse" %}</span>
                        </p>
                        <input type="file" name="file" id="fileInput" class="form-control-px360" 
                               accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png"
                               {% if not document %}required{% endif %}>
                        <small class="text-slate-500 text-xs block mt-2">
                            {% trans "Supported: PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, JPG, PNG (Max 100MB)" %}
                        </small>
                    </div>

                    {% if document %}
                    <div class="flex items-center gap-2 mt-4 p-3 bg-slate-50 rounded-lg">
                        <input type="checkbox" name="new_version" id="newVersionCheck" class="w-4 h-4 text-navy rounded">
                        <label for="newVersionCheck" class="text-sm text-gray-700 font-medium">
                            {% trans "Upload as new version" %}
                        </label>
                    </div>
                    {% endif %}
                </div>

                <!-- Document Details -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i data-lucide="info" class="w-5 h-5"></i>{{ _("Document Information")}}
                    </h5>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1.5 required-field">{% trans "Title (English)" %}</label>
                        <input type="text" name="title" class="form-control-px360" 
                               value="{% if form.title.value %}{{ form.title.value }}{% elif document %}{{ document.title }}{% endif %}"
                               placeholder="{% trans 'Enter document title' %}" required>
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1.5">{% trans "Title (Arabic)" %}</label>
                        <input type="text" name="title_ar" class="form-control-px360" dir="rtl"
                               value="{% if form.title_ar.value %}{{ form.title_ar.value }}{% elif document %}{{ document.title_ar }}{% endif %}">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1.5">{% trans "Description (English)" %}</label>
                        <textarea name="description" class="form-control-px360" rows="4">{% if form.description.value %}{{ form.description.value }}{% elif document %}{{ document.description }}{% endif %}</textarea>
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1.5">{% trans "Description (Arabic)" %}</label>
                        <textarea name="description_ar" class="form-control-px360" rows="4" dir="rtl">{% if form.description_ar.value %}{{ form.description_ar.value }}{% elif document %}{{ document.description_ar }}{% endif %}</textarea>
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1.5{% if not folder %} required-field{% endif %}">{% trans "Folder" %}</label>
                        <select name="folder" class="form-select-px360" {% 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 }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1.5">{% trans "Tags" %}</label>
                        <input type="text" name="tags" class="form-control-px360"
                               value="{% if form.tags.value %}{{ form.tags.value }}{% elif document %}{{ document.tags }}{% endif %}"
                               placeholder="{% trans 'Comma-separated tags' %}">
                    </div>
                </div>

                <!-- Access Control -->
                <div class="form-section">
                    <h5 class="form-section-title">
                        <i data-lucide="shield" class="w-5 h-5"></i>{{ _("Access Control")}}
                    </h5>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">{% trans "Access Roles" %}</label>
                        <div class="border-2 border-gray-200 rounded-lg p-4 max-h-48 overflow-y-auto">
                            {% for choice in form.access_roles %}
                            <div class="flex items-center gap-2 mb-2">
                                {{ choice.tag }}
                                <label for="{{ choice.id_for_label }}" class="text-sm text-gray-700">{{ choice.choice_label }}</label>
                            </div>
                            {% endfor %}
                        </div>
                    </div>

                    <div class="flex items-center gap-2 p-3 bg-slate-50 rounded-lg">
                        <input type="checkbox" name="is_published" id="isPublishedCheck" class="w-4 h-4 text-navy rounded"
                               {% if not document or document.is_published %}checked{% endif %}>
                        <label for="isPublishedCheck" class="text-sm text-gray-700 font-medium">
                            {% trans "Publish this document" %}
                        </label>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="lg:col-span-1">
                <!-- Guidelines -->
                <div class="alert-info-px360 mb-4">
                    <h6 class="font-semibold text-navy mb-2 flex items-center gap-2">
                        <i data-lucide="info" class="w-5 h-5"></i>{{ _("Guidelines")}}
                    </h6>
                    <ul class="text-xs text-slate-600 space-y-1 list-disc list-inside">
                        <li>{{ _("Use descriptive titles")}}</li>
                        <li>{{ _("Add clear descriptions")}}</li>
                        <li>{{ _("Set appropriate visibility")}}</li>
                        <li>{{ _("Use tags for searching")}}</li>
                    </ul>
                </div>

                <!-- Current Info -->
                {% if document %}
                <div class="alert-secondary-px360 mb-4">
                    <h6 class="font-semibold text-slate-700 mb-2 flex items-center gap-2">
                        <i data-lucide="file-text" class="w-5 h-5"></i>{{ _("Current Document")}}
                    </h6>
                    <ul class="text-xs text-slate-600 space-y-1">
                        <li><strong>{{ _("Created:") }}</strong> {{ document.created_at|date:"M d, Y" }}</li>
                        <li><strong>{{ _("Updated:") }}</strong> {{ document.updated_at|date:"M d, Y" }}</li>
                        <li><strong>{{ _("Version:") }}</strong> {{ document.version }}</li>
                    </ul>
                </div>
                {% endif %}

                <!-- Action Buttons -->
                <div class="flex flex-col gap-2 sticky top-4">
                    <button type="submit" class="hh-btn hh-btn-primary justify-center shadow-lg">
                        <i data-lucide="check-circle" class="w-5 h-5"></i>
                        {% if document %}{{ _("Update")}}{% else %}{{ _("Upload")}}{% endif %}
                    </button>
                    <a href="{% if folder %}{% url 'references:folder_view' folder.id %}{% else %}{% url 'references:dashboard' %}{% endif %}" 
                       class="hh-btn hh-btn-secondary justify-center">
                        <i data-lucide="x-circle" class="w-5 h-5"></i>{{ _("Cancel")}}
                    </a>
                </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 = '#005696';
        this.style.backgroundColor = '#e7f3ff';
    });

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

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

        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.setAttribute('data-lucide', 'file-check');
        icon.classList.remove('text-slate-400');
        icon.classList.add('text-green-600');
        p.innerHTML = `<strong class="text-gray-800">${fileName}</strong><br><span class="text-slate-500 text-sm">{% trans "File selected" %}</span>`;
        lucide.createIcons();
    }

    // Form validation
    form.addEventListener('submit', function(e) {
        const maxSize = 100 * 1024 * 1024;
        if (fileInput.files.length > 0 && fileInput.files[0].size > maxSize) {
            e.preventDefault();
            alert('{% trans "File size exceeds the 100MB limit." %}');
            return;
        }
        if (!form.checkValidity()) {
            e.preventDefault();
            e.stopPropagation();
        }
        form.classList.add('was-validated');
    });
});
</script>
{% endblock %}
