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

{% block extra_css %}
    <link rel="stylesheet" href="{% static 'simplemde/simplemde.min.css' %}">
    <style>
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 4px;
        }
        .select2-container--classic .select2-selection--multiple {
            border: 1px solid #d1d5db !important;
            border-radius: 0.375rem !important;
            min-height: 38px !important;
        }
        .select2-container--classic .select2-selection--multiple .select2-selection__choice {
            background-color: #e5e7eb !important;
            border: 1px solid #d1d5db !important;
            border-radius: 0.25rem !important;
            padding: 2px 8px !important;
            margin: 3px !important;
        }
    </style>
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="bg-white shadow-md rounded-lg overflow-hidden">
        <div class="px-4 py-5 sm:px-6 bg-gray-50 border-b border-gray-200">
            <h1 class="text-2xl font-bold text-gray-900">
                {% if form.instance.pk %}{% trans "Edit Link" %}{% else %}{% trans "New Link" %}{% endif %}
            </h1>
        </div>
        <div class="px-4 py-5 sm:p-6">
            <!-- Link Type Tabs -->
            <div class="mb-4">
                <div class="flex border-b border-gray-200">
                    <button type="button" class="py-2 px-4 text-sm font-medium text-center {% if not is_custom %}text-blue-600 border-b-2 border-blue-600{% else %}text-gray-500 border-b-2 border-transparent{% endif %} hover:text-blue-700 hover:border-blue-700 focus:outline-none" id="link-tab">
                        {% trans "Link" %}
                    </button>
                    <button type="button" class="py-2 px-4 text-sm font-medium text-center {% if is_custom %}text-blue-600 border-b-2 border-blue-600{% else %}text-gray-500 border-b-2 border-transparent{% endif %} hover:text-gray-700 hover:border-gray-300 focus:outline-none" id="custom-tab">
                        {% trans "Custom" %}
                    </button>
                </div>
            </div>

            <!-- Link Type Description -->
            <div id="link-description" class="bg-blue-50 border-l-4 border-blue-400 p-4 mb-4 {% if is_custom %}hidden{% endif %}">
                <p class="text-sm text-blue-700">
                    {% trans "Link type is used for redirecting to an external URL. Use this when you want to create a short alias for a long URL." %}
                </p>
            </div>
            <div id="custom-description" class="bg-green-50 border-l-4 border-green-400 p-4 mb-4 {% if not is_custom %}hidden{% endif %}">
                <p class="text-sm text-green-700">
                    {% trans "Custom type allows you to create a link with custom HTML content. Use this when you want to display a message or custom content instead of redirecting." %}
                </p>
            </div>
            <div id="template-description" class="bg-purple-50 border-l-4 border-purple-400 p-4 mb-4 {% if is_custom %}hidden{% endif %}">
                <p class="text-sm text-purple-700">
                    {% trans "Template type allows you to create dynamic URLs with parameters. Use {query, default=value} syntax in the URL." %}
                </p>
                <p class="text-sm text-purple-700 mt-2">
                    {% trans "Example: https://google.com/search?q={query, default=hello}" %}
                </p>
            </div>

            <!-- Form -->
            <form method="post" class="space-y-6">
                {% csrf_token %}
                <input type="hidden" name="link_type" id="id_link_type" value="{{ form.link_type.value|default:'LINK' }}">
                {% for field in form %}
                    {% if field.name != 'link_type' %}
                        <!-- Render fields based on link type -->
                        <div class="space-y-1 {% if field.name == 'original_url' %}link-field{% if is_custom %}hidden{% endif %}{% elif field.name == 'text' %} custom-field {% if not is_custom %}hidden{% endif %}{% endif %}">
                            <label for="{{ field.id_for_label }}" class="block text-sm font-medium text-gray-700 {% if field.name == 'original_url' and is_custom or field.name == 'text' and not is_custom %}hidden{% endif %} {% if field.name != 'description' %}required-field{% endif %}">
                                {{ field.label }}
                            </label>
                            <div class="mt-1">
                                {% if field.name == 'text' %}
                                    <!-- Render text field only for custom links -->
                                    {% if is_custom or is_new %}
                                        {{ field }}
                                    {% endif %}
                                {% elif field.name == 'original_url' %}
                                    <!-- Render original_url field only for default links -->
                                    {% if not is_custom %}
                                        <input type="{{ field.field.widget.input_type }}"
                                               name="{{ field.name }}"
                                               id="{{ field.id_for_label }}"
                                               value="{{ field.value|default_if_none:'' }}"
                                               class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                               {% if field.field.required %}required{% endif %}>
                                    {% endif %}
                                {% elif field.name == 'alias' and form.instance.pk %}
                                    <!-- Render alias field as read-only when editing -->
                                    <input type="text"
                                           name="{{ field.name }}"
                                           id="{{ field.id_for_label }}"
                                           value="{{ field.value|default_if_none:'' }}"
                                           class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                           readonly>
                                    <p class="mt-2 text-sm text-yellow-600">{% trans "Alias cannot be changed after creation." %}</p>
                                {% elif field.name == 'tags' %}
                                    <!-- Render tags field with Select2 -->
                                    {{ field }}
                                {% else %}
                                    <!-- Render other fields normally -->
                                    <input type="{{ field.field.widget.input_type }}"
                                           name="{{ field.name }}"
                                           id="{{ field.id_for_label }}"
                                           value="{{ field.value|default_if_none:'' }}"
                                           class="shadow appearance-none rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                                           {% if field.field.required %}required{% endif %}>
                                {% endif %}
                            </div>
                            {% if field.errors %}
                                <ul class="mt-1 text-sm text-red-600">
                                    {% for error in field.errors %}
                                        <li>{{ error }}</li>
                                    {% endfor %}
                                </ul>
                            {% endif %}
                            {% if field.help_text %}
                                <p class="mt-2 text-sm text-gray-500">{{ field.help_text }}</p>
                            {% endif %}
                        </div>
                    {% endif %}
                {% endfor %}
                <div class="flex justify-end space-x-3 mt-6">
                    <a href="{% url 'link_list' %}" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-gray-700 bg-gray-200 hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-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>
            </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>
        $(document).ready(function() {
            // Initialize Select2 for tags
            $('#id_tags').select2({
                theme: 'classic',
                width: '100%',
                placeholder: '{% trans "Select tags" %}',
                allowClear: true,
                tags: true, // Allow creating new tags
                tokenSeparators: [',', ' '],
                createTag: function(params) {
                    var term = $.trim(params.term).toLowerCase();
                    if (term === '') {
                        return null;
                    }
                    return {
                        id: term,
                        text: term,
                        newTag: true
                    };
                }
            });
        });
        document.addEventListener('DOMContentLoaded', function() {
            const linkTab = document.getElementById('link-tab');
            const customTab = document.getElementById('custom-tab');
            const linkFields = document.querySelectorAll('.link-field');
            const customFields = document.querySelectorAll('.custom-field');
            const linkDescription = document.getElementById('link-description');
            const customDescription = document.getElementById('custom-description');
            const linkTypeInput = document.getElementById('id_link_type');
            const textField = document.querySelector('.custom-field');
            let simplemde = null;

            function showLinkFields() {
                linkTab.classList.add('text-blue-600', 'border-blue-600');
                linkTab.classList.remove('text-gray-500', 'border-transparent');
                customTab.classList.remove('text-blue-600', 'border-blue-600');
                customTab.classList.add('text-gray-500', 'border-transparent');
                linkFields.forEach(field => {
                    field.classList.remove('hidden');
                    const label = field.querySelector('label');
                    if (label) label.classList.remove('hidden');
                });
                customFields.forEach(field => {
                    field.classList.add('hidden');
                    const label = field.querySelector('label');
                    if (label) label.classList.add('hidden');
                });
                linkDescription.classList.remove('hidden');
                customDescription.classList.add('hidden');
                linkTypeInput.value = 'LINK';
                textField.classList.add('hidden');
            }

            function showCustomFields() {
                customTab.classList.add('text-blue-600', 'border-blue-600');
                customTab.classList.remove('text-gray-500', 'border-transparent');
                linkTab.classList.remove('text-blue-600', 'border-blue-600');
                linkTab.classList.add('text-gray-500', 'border-transparent');
                customFields.forEach(field => {
                    field.classList.remove('hidden');
                    const label = field.querySelector('label');
                    if (label) label.classList.remove('hidden');
                });
                linkFields.forEach(field => {
                    field.classList.add('hidden');
                    const label = field.querySelector('label');
                    if (label) label.classList.add('hidden');
                });
                customDescription.classList.remove('hidden');
                linkDescription.classList.add('hidden');
                linkTypeInput.value = 'CUSTOM';
                textField.classList.remove('hidden');
                initializeSimpleMDE();
            }

            function initializeSimpleMDE() {
                if (!simplemde) {
                    var textArea = document.getElementById('id_text');
                    if (textArea) {
                        // Clear any SimpleMDE autosave cache to ensure we use the latest DB content
                        // This is important after task list updates
                        var linkId = '{{ form.instance.pk|default:"new" }}';
                        var cacheKey = 'smde_link_text_' + linkId;
                        localStorage.removeItem(cacheKey);

                        simplemde = new SimpleMDE({
                            element: textArea,
                            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"
                            ]
                        });
                    }
                }
            }

            linkTab.addEventListener('click', showLinkFields);
            customTab.addEventListener('click', showCustomFields);

            // Initialize form state
            if (linkTypeInput.value === 'CUSTOM') {
                showCustomFields();
            } else {
                showLinkFields();
            }

            // Check if we're creating a new link
            const isNewLink = {{ form.instance.pk|yesno:"false,true" }};
            if (isNewLink) {
                // Hide text field by default for new links
                textField.classList.add('hidden');
            }
        });
    </script>
{% endblock %}
