{% extends "admin/admin_base.html" %}
{% load i18n static %}

{% block admin_title %}{{ title }}{% endblock %}

{% block extra_head %}
{{ block.super }}
<link href="{% static "dist/main.css" %}" rel="stylesheet">
<script src="{% static "dist/main.js" %}" defer></script>
<style>
    /* Ensure EasyMDE fits well with BeerCSS containers */
    .editor-toolbar {
        background: var(--surface-variant) !important;
        color: var(--on-surface-variant) !important;
        border-color: var(--outline) !important;
        opacity: 1 !important;
    }
    .CodeMirror {
        background: var(--surface) !important;
        color: var(--on-surface) !important;
        border-color: var(--outline) !important;
    }
    .editor-toolbar button {
        color: var(--on-surface-variant) !important;
    }
    .editor-toolbar button.active, .editor-toolbar button:hover {
        background: var(--primary-container) !important;
        color: var(--on-primary-container) !important;
    }
    /* Add spacing between sections */
    .form-section {
        margin-bottom: 2rem;
    }
    /* Cropper styles */
    .cropper-container {
        max-height: 70vh;
    }
    #cropper-image {
        display: block;
        max-width: 100%;
    }
</style>
{% endblock %}

{% block content %}
<form method="post" enctype="multipart/form-data" id="recipe-form">
    {% csrf_token %}
    {{ form.rotation }}
    {{ form.image_data }}
    <div class="grid">
        <!-- Top Section: Title, Tags, and Image -->
        <div class="s12 m8">
            <article class="round padding border mb-2">
                <div class="field label border round">
                    {{ form.title }}
                    <label>{{ form.title.label }}</label>
                    {% if form.title.errors %}<span class="error">{{ form.title.errors|striptags }}</span>{% endif %}
                </div>

                <div class="field label border round mt-1">
                    {{ form.tags_string }}
                    <label>{{ form.tags_string.label }}</label>
                    {% if form.tags_string.errors %}<span class="error">{{ form.tags_string.errors|striptags }}</span>{% endif %}
                    <span class="helper">{% trans "Separate tags with commas. New tags will be created automatically." %}</span>
                </div>

                <div class="field label border round mt-1">
                    {{ form.uploaded_by }}
                    <label>{{ form.uploaded_by.label }}</label>
                    {% if form.uploaded_by.errors %}<span class="error">{{ form.uploaded_by.errors|striptags }}</span>{% endif %}
                </div>

                <div class="field label border round mt-1">
                    {{ form.price }}
                    <label>{{ form.price.label }}</label>
                    {% if form.price.errors %}<span class="error">{{ form.price.errors|striptags }}</span>{% endif %}
                </div>

                <div class="field label border round mt-1">
                    {{ form.max_daily_orders }}
                    <label>{{ form.max_daily_orders.label }}</label>
                    {% if form.max_daily_orders.errors %}<span class="error">{{ form.max_daily_orders.errors|striptags }}</span>{% endif %}
                </div>

                <div class="field middle-align mt-1">
                    <label class="checkbox">
                        {{ form.is_highlighted }}
                        <span>{{ form.is_highlighted.label }}</span>
                    </label>
                </div>

                <div class="field middle-align mt-1">
                    <label class="checkbox">
                        {{ form.is_approved }}
                        <span>{{ form.is_approved.label }}</span>
                    </label>
                </div>
            </article>

            <!-- Description -->
            <div class="form-section">
                <div class="row align-center mb-1">
                    <i class="primary-text">description</i>
                    <h6 class="bold ml-1">{% trans "Description" %}</h6>
                </div>
                <div class="card border no-padding">
                    {{ form.description }}
                </div>
                {% if form.description.errors %}<span class="error">{{ form.description.errors|striptags }}</span>{% endif %}
            </div>
        </div>

        <div class="s12 m4">
            <article class="round padding border center-align">
                <h6 class="bold mb-1">{% trans "Recipe Image" %}</h6>

                <div class="relative mb-1" style="overflow: hidden; min-height: 200px; display: flex; align-items: center; justify-content: center;">
                    {% if recipe.image %}
                    <img src="{{ recipe.image_medium.url }}?v={% now "U" %}" class="responsive round" id="image-preview" style="max-height: 300px; width: 100%; object-fit: contain;">
                    {% else %}
                    <img src="" class="responsive round" id="image-preview" style="max-height: 300px; width: 100%; object-fit: contain; display: none;">
                    <div class="medium-height middle-align center-align gray1 round" id="image-placeholder" style="width: 100%;">
                        <i class="extra">image</i>
                    </div>
                    {% endif %}
                </div>

                <div id="image-tools" class="row no-space border round mb-1" style="{% if not recipe.image %}display: none;{% endif %}">
                    <button type="button" class="button transparent max" onclick="openCropper()" title="{% trans 'Edit Image' %}">
                        <i>crop_rotate</i>
                        <span>{% trans "Edit" %}</span>
                    </button>
                </div>

                <div class="field file border round">
                    <input type="text" readonly>
                    {{ form.image }}
                    <label>{{ form.image.label }}</label>
                    <i>publish</i>
                </div>
                {% if form.image.errors %}<span class="error">{{ form.image.errors|striptags }}</span>{% endif %}
            </article>
        </div>

        <!-- Ingredients and Instructions (Full Width) -->
        <div class="s12">
            <div class="divider mb-2"></div>

            <div class="form-section">
                <div class="row align-center mb-1">
                    <i class="primary-text">shopping_cart</i>
                    <h6 class="bold ml-1">{% trans "Ingredients" %}</h6>
                </div>
                <div class="card border no-padding">
                    {{ form.ingredients }}
                </div>
                {% if form.ingredients.errors %}<span class="error">{{ form.ingredients.errors|striptags }}</span>{% endif %}
            </div>

            <div class="form-section">
                <div class="row align-center mb-1">
                    <i class="primary-text">list</i>
                    <h6 class="bold ml-1">{% trans "Instructions" %}</h6>
                </div>
                <div class="card border no-padding">
                    {{ form.instructions }}
                </div>
                {% if form.instructions.errors %}<span class="error">{{ form.instructions.errors|striptags }}</span>{% endif %}
            </div>
        </div>
    </div>

    <div class="large-space"></div>
    <nav class="right-align padding surface-container border round">
        <a href="{% url 'admin_recipe_list' %}" class="button transparent">{% trans "Cancel" %}</a>
        <button type="submit" class="button primary round">
            <i>save</i>
            <span>{% trans "Save Recipe" %}</span>
        </button>
    </nav>
</form>

<dialog id="cropper-dialog" class="large">
    <div class="padding">
        <h5 class="bold mb-1">{% trans "Edit Image" %}</h5>
        <div class="cropper-container mb-1">
            <cropper-canvas id="cropper-canvas" background style="height: 500px;">
                <cropper-image id="cropper-image" src="" rotatable scalable skewable translatable></cropper-image>
                <cropper-shade hidden></cropper-shade>
                <cropper-handle action="select" plain></cropper-handle>
                <cropper-selection id="cropper-selection" initial-coverage="0.5" movable resizable>
                    <cropper-grid role="grid" covered></cropper-grid>
                    <cropper-crosshair centered></cropper-crosshair>
                    <cropper-handle action="move" theme-color="rgba(255, 255, 255, 0.35)"></cropper-handle>
                    <cropper-handle action="n-resize"></cropper-handle>
                    <cropper-handle action="e-resize"></cropper-handle>
                    <cropper-handle action="s-resize"></cropper-handle>
                    <cropper-handle action="w-resize"></cropper-handle>
                    <cropper-handle action="ne-resize"></cropper-handle>
                    <cropper-handle action="nw-resize"></cropper-handle>
                    <cropper-handle action="se-resize"></cropper-handle>
                    <cropper-handle action="sw-resize"></cropper-handle>
                </cropper-selection>
            </cropper-canvas>
        </div>
        <div class="row scroll no-space border round mb-1">
            <button type="button" class="button transparent max" onclick="rotateImage(-90)" title="{% trans 'Rotate Left' %}">
                <i>rotate_left</i>
            </button>
            <button type="button" class="button transparent max" onclick="rotateImage(90)" title="{% trans 'Rotate Right' %}">
                <i>rotate_right</i>
            </button>
            <div class="divider vertical"></div>
            <button type="button" class="button transparent max" onclick="flipImageHorizontal()" title="{% trans 'Flip Horizontal' %}">
                <i>flip</i>
            </button>
            <button type="button" class="button transparent max" onclick="flipImageVertical()" title="{% trans 'Flip Vertical' %}">
                <i>flip</i>
            </button>
            <div class="divider vertical"></div>
            <button type="button" class="button transparent max" onclick="setAspectRatio(1)" title="{% trans '1:1' %}">1:1</button>
            <button type="button" class="button transparent max" onclick="setAspectRatio(4/3)" title="{% trans '4:3' %}">4:3</button>
            <button type="button" class="button transparent max" onclick="setAspectRatio(16/9)" title="{% trans '16:9' %}">16:9</button>
            <button type="button" class="button transparent max" onclick="setAspectRatio(NaN)" title="{% trans 'Free' %}">
                <i>crop_free</i>
            </button>
        </div>
        <nav class="right-align">
            <button type="button" class="button transparent" onclick="ui('#cropper-dialog')">{% trans "Cancel" %}</button>
            <button type="button" class="button primary" onclick="applyCrop()">{% trans "Apply" %}</button>
        </nav>
    </div>
</dialog>
{% endblock %}

{% block admin_scripts %}
<script>
    const imagePreview = document.getElementById('image-preview');
    const imagePlaceholder = document.getElementById('image-placeholder');
    const imageTools = document.getElementById('image-tools');
    const imageInput = document.getElementById('id_image');
    const imageDataInput = document.getElementById('id_image_data');
    const cropperImage = document.getElementById('cropper-image');
    const cropperCanvas = document.getElementById('cropper-canvas');
    const cropperSelection = document.getElementById('cropper-selection');
    
    let currentScaleX = 1;
    let currentScaleY = 1;

    function openCropper() {
        if (!imagePreview.src || imagePreview.src === window.location.href) return;
        cropperImage.src = imagePreview.src;
        ui('#cropper-dialog');
    }

    function rotateImage(angle) {
        const radians = (angle * Math.PI) / 180;
        cropperImage.$rotate(radians);
    }

    function flipImageHorizontal() {
        currentScaleX = -currentScaleX;
        cropperImage.$scale(currentScaleX, currentScaleY);
    }

    function flipImageVertical() {
        currentScaleY = -currentScaleY;
        cropperImage.$scale(currentScaleX, currentScaleY);
    }

    function setAspectRatio(ratio) {
        cropperSelection.aspectRatio = isNaN(ratio) ? NaN : ratio;
    }

    async function applyCrop() {
        try {
            const canvas = await cropperSelection.$toCanvas({
                maxWidth: 2000,
                maxHeight: 2000,
            });

            const croppedData = canvas.toDataURL('image/jpeg', 0.9);
            imagePreview.src = croppedData;
            imagePreview.style.display = 'block';
            if (imagePlaceholder) imagePlaceholder.style.display = 'none';
            imageTools.style.display = 'flex';
            imageDataInput.value = croppedData;

            ui('#cropper-dialog');
        } catch (error) {
            console.error('Error cropping image:', error);
        }
    }

    imageInput.addEventListener('change', function(e) {
        const files = e.target.files;
        if (files && files.length > 0) {
            const reader = new FileReader();
            reader.onload = function(event) {
                imagePreview.src = event.target.result;
                imagePreview.style.display = 'block';
                if (imagePlaceholder) imagePlaceholder.style.display = 'none';
                imageTools.style.display = 'flex';
                // Reset transformation state
                currentScaleX = 1;
                currentScaleY = 1;
                // Automatically open cropper for new images
                openCropper();
            };
            reader.readAsDataURL(files[0]);
        }
    });

    document.addEventListener('DOMContentLoaded', function() {
        const fields = ['id_description', 'id_ingredients', 'id_instructions'];
        fields.forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                new EasyMDE({
                    element: el,
                    spellChecker: false,
                    autosave: {
                        enabled: false
                    },
                    status: false,
                    minHeight: "200px"
                });
            }
        });
    });
</script>
{% endblock %}
