{% extends 'base.html' %}
{% load i18n %}
{% load static %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'simplemde/simplemde.min.css' %}">
{# Select2 CSS is loaded globally from vendor in base.html #}
<style>
    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        justify-content: center;
        align-items: center;
    }
    .loading-container {
        background: white;
        padding: 2rem;
        border-radius: 0.5rem;
        text-align: center;
    }
    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 1rem auto;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    /* SimpleMDE customization */
    .CodeMirror {
        height: 300px;
        border-radius: 0.375rem;
    }
    .editor-toolbar {
        border-top-left-radius: 0.375rem;
        border-top-right-radius: 0.375rem;
    }
    .CodeMirror {
        border-bottom-left-radius: 0.375rem;
        border-bottom-right-radius: 0.375rem;
    }
</style>
{% endblock %}

{% block content %}
<!-- Loading Overlay -->
<div id="loadingOverlay" class="overlay">
    <div class="loading-container">
        <div class="loading-spinner"></div>
        <p class="text-gray-700">{% trans "Fetching page information..." %}</p>
        <p class="text-sm text-gray-500">{% trans "This may take a few seconds" %}</p>
    </div>
</div>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="bg-white shadow-sm rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:p-6">
            <h1 class="text-2xl font-bold text-gray-900 mb-6">
                {% if form.instance.pk %}
                    {% trans "Edit Page" %}
                {% else %}
                    {% trans "New Bookmark Page" %}
                {% endif %}
            </h1>

            <form method="post" class="space-y-6">
                {% csrf_token %}

                <div class="space-y-6">
                    <!-- URL Field -->
                    <div>
                        <label for="{{ form.url.id_for_label }}" class="block text-sm font-medium text-gray-700">
                            {{ form.url.label }}
                        </label>
                        <div class="mt-1">
                            <input type="url" name="{{ form.url.name }}" id="{{ form.url.id_for_label }}"
                                   class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                   value="{{ form.url.value|default:'' }}"
                                   placeholder="https://example.com">
                        </div>
                        <div id="urlError" class="mt-2 text-sm text-red-600 hidden"></div>
                        {% if form.url.errors %}
                        <p class="mt-2 text-sm text-red-600">{{ form.url.errors.0 }}</p>
                        {% endif %}
                    </div>

                    <!-- Title Field -->
                    <div>
                        <label for="{{ form.title.id_for_label }}" class="block text-sm font-medium text-gray-700">
                            {{ form.title.label }}
                        </label>
                        <div class="mt-1">
                            <input type="text" name="{{ form.title.name }}" id="{{ form.title.id_for_label }}"
                                   class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                   value="{{ form.title.value|default:'' }}"
                                   placeholder="Page Title">
                        </div>
                        {% if form.title.errors %}
                        <p class="mt-2 text-sm text-red-600">{{ form.title.errors.0 }}</p>
                        {% endif %}
                    </div>

                    <!-- Summary Field -->
                    <div>
                        <label for="{{ form.summary.id_for_label }}" class="block text-sm font-medium text-gray-700">
                            {{ form.summary.label }}
                        </label>
                        <div class="mt-1">
                            <textarea name="{{ form.summary.name }}" id="{{ form.summary.id_for_label }}" rows="3"
                                      class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                      placeholder="Brief summary of the page">{{ form.summary.value|default:'' }}</textarea>
                        </div>
                        {% if form.summary.errors %}
                        <p class="mt-2 text-sm text-red-600">{{ form.summary.errors.0 }}</p>
                        {% endif %}
                    </div>

                    <!-- Content Field with SimpleMDE -->
                    <div>
                        <label for="{{ form.content.id_for_label }}" class="block text-sm font-medium text-gray-700">
                            {{ form.content.label }}
                        </label>
                        <div class="mt-1">
                            <textarea name="{{ form.content.name }}"
                                     id="{{ form.content.id_for_label }}"
                                     class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border border-gray-300 rounded-md">{{ form.content.value|default:'' }}</textarea>
                        </div>
                        {% if form.content.errors %}
                        <p class="mt-2 text-sm text-red-600">{{ form.content.errors.0 }}</p>
                        {% endif %}
                        <p class="mt-2 text-sm text-gray-500">{% trans "Supports Markdown formatting" %}</p>
                    </div>
                    <!-- Tags Field -->
                    <div>
                        <label for="{{ form.tags.id_for_label }}" class="block text-sm font-medium text-gray-700">
                            {{ form.tags.label }}
                        </label>
                        <div class="mt-1">
                            {{ form.tags }}
                        </div>
                        {% if form.tags.errors %}
                        <p class="mt-2 text-sm text-red-600">{{ form.tags.errors.0 }}</p>
                        {% endif %}
                    </div>

                    <!-- Reset Status Checkbox - Only show for editing -->
                    {% if form.instance.pk %}
                    <div class="relative flex items-start">
                        <div class="flex items-center h-5">
                            <input type="checkbox"
                                   name="reset_status"
                                   id="reset_status"
                                   class="focus:ring-blue-500 h-4 w-4 text-blue-600 border-gray-300 rounded">
                        </div>
                        <div class="ml-3 text-sm">
                            <label for="reset_status" class="font-medium text-gray-700">
                                {% trans "Reset processing status" %}
                            </label>
                            <p class="text-gray-500">
                                {% trans "Reset the page status to pending and trigger re-fetching of page information" %}
                            </p>
                        </div>
                    </div>
                    {% endif %}
                </div>

                <div class="pt-5">
                    <div class="flex justify-end space-x-3">
                        <a href="{% url 'page-list' %}"
                           class="inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            {% trans "Cancel" %}
                        </a>
                        <button type="submit"
                                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            {% trans "Save" %}
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'simplemde/simplemde.min.js' %}"></script>
{# jQuery and Select2 are loaded globally from vendor in base.html #}
<script>
// Clear SimpleMDE autosave cache to prevent old cached content from overriding DB updates
// This is especially important after task list checkbox toggles
var pageId = '{{ form.instance.pk|default:"new" }}';
var cacheKey = 'smde_page_content_' + pageId;
if (pageId !== 'new') {
    // Check if the cached timestamp is older than the updated_at timestamp
    var cachedData = localStorage.getItem(cacheKey);
    if (cachedData) {
        try {
            var parsedCache = JSON.parse(cachedData);
            var updatedAt = new Date('{{ form.instance.updated_at.isoformat }}').getTime();
            var cacheTime = parsedCache.ts || 0;
            // If cache is older than last update, clear it
            if (cacheTime < updatedAt) {
                localStorage.removeItem(cacheKey);
            }
        } catch (e) {
            // If parsing fails, clear the cache
            localStorage.removeItem(cacheKey);
        }
    }
}

// Initialize SimpleMDE with custom task list button
var simplemde = new SimpleMDE({
    element: document.getElementById("{{ form.content.id_for_label }}"),
    spellChecker: false,
    autosave: {
        enabled: true,
        unique_id: "page_content_{{ form.instance.pk|default:'new' }}"
    },
    toolbar: [
        "bold", "italic", "heading", "|",
        "quote", "unordered-list", "ordered-list", "|",
        {
            name: "task-list",
            action: function customTaskList(editor) {
                var cm = editor.codemirror;
                var selection = cm.getSelection();
                var lines = selection.split('\n');

                if (lines.length > 0 && lines[0].match(/^- \[[ xX]\] /)) {
                    // Remove task list formatting
                    var newText = lines.map(function(line) {
                        return line.replace(/^- \[[ xX]\] /, '- ');
                    }).join('\n');
                    cm.replaceSelection(newText);
                } else if (selection) {
                    // Add task list formatting to selection
                    var newText = lines.map(function(line) {
                        if (line.trim()) {
                            return '- [ ] ' + line.replace(/^[-*]\s*/, '');
                        }
                        return line;
                    }).join('\n');
                    cm.replaceSelection(newText);
                } else {
                    // Insert a single task list item
                    cm.replaceSelection('- [ ] ');
                }
                cm.focus();
            },
            className: "fa fa-check-square",
            title: "Task List (- [ ] item)",
        },
        "|",
        "link", "image", "table", "|",
        "preview", "side-by-side", "fullscreen", "|",
        "guide"
    ],
    status: ["autosave", "lines", "words", "cursor"],
    renderingConfig: {
        singleLineBreaks: false,
        codeSyntaxHighlighting: true,
    }
});

// Existing URL fetching JavaScript
let fetchTimeout;
const urlInput = document.getElementById('{{ form.url.id_for_label }}');
const titleInput = document.getElementById('{{ form.title.id_for_label }}');
const summaryInput = document.getElementById('{{ form.summary.id_for_label }}');
const errorDiv = document.getElementById('urlError');
const loadingOverlay = document.getElementById('loadingOverlay');

urlInput.addEventListener('input', function(e) {
    clearTimeout(fetchTimeout);
    errorDiv.classList.add('hidden');

    if (!urlInput.value) return;

    fetchTimeout = setTimeout(() => {
        if (urlInput.checkValidity()) {
            fetchPageInfo(urlInput.value);
        }
    }, 500);
});

async function fetchPageInfo(url) {
    loadingOverlay.style.display = 'flex';
    errorDiv.classList.add('hidden');

    // Set timeout
    const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('Request timed out')), 5000);  // 5 second timeout
    });

    try {
        const response = await Promise.race([
            fetch(`/fetch-page-info/?url=${encodeURIComponent(url)}`),
            timeoutPromise
        ]);

        const data = await response.json();

        if (response.ok) {
            if (!titleInput.value) {
                titleInput.value = data.title || '';
            }
            if (!summaryInput.value) {
                summaryInput.value = data.summary || '';
            }
        } else {
            throw new Error(data.error);
        }
    } catch (error) {
        errorDiv.textContent = error.message || 'Failed to fetch page information';
        errorDiv.classList.remove('hidden');
    } finally {
        loadingOverlay.style.display = 'none';
    }
}
</script>

<script>
    $(document).ready(function() {
        // Initialize Select2
        $('.select2').select2({
            theme: 'classic',
            width: '100%'
        });
    });
</script>
{% endblock %}
