{% extends "dashboard/base.html" %}

{% block page_title %}{% if editing %}Edit Product{% else %}Add Product{% endif %}{% endblock %}

{% block dashboard_content %}
<div class="card" style="max-width:700px;">
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="form-group">
            <label class="form-label">Product Name</label>
            <input type="text" name="name" class="form-input" required placeholder="e.g. Cotton T-Shirt" value="{% if product %}{{ product.name }}{% endif %}">
        </div>
        <div class="form-group">
            <label class="form-label">Base Price (GHS)</label>
            <input type="number" name="base_price" class="form-input" step="0.01" min="0" required placeholder="0.00" value="{% if product %}{{ product.base_price }}{% endif %}">
            <span class="form-hint">Reference price only. You set the actual sale price when creating a sale.</span>
        </div>
        <div class="form-group">
            <label class="form-label">Description</label>
            <textarea name="description" class="form-textarea" rows="4" placeholder="Describe your product...">{% if product %}{{ product.description }}{% endif %}</textarea>
        </div>

        {% if editing and product.images.all %}
        <div class="form-group">
            <label class="form-label">Current Images</label>
            <div class="flex gap-3 flex-wrap">
                {% for img in product.images.all %}
                <div style="position:relative;">
                    <img src="{{ img.image.url }}" alt="" style="width:100px;height:100px;border-radius:var(--radius-sm);object-fit:cover;border:2px solid var(--color-border-light);">
                    <button type="button" onclick="deleteImage('{{ img.id }}')" style="position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;background:var(--color-error);color:white;border:none;cursor:pointer;font-size:12px;display:flex;align-items:center;justify-content:center;">x</button>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}

        <div class="form-group">
            <label class="form-label">{% if editing %}Add More Images{% else %}Product Images{% endif %} (up to 3 - Auto-Compressed)</label>
            <div class="image-upload" onclick="document.getElementById('imageInput').click();">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-muted)" stroke-width="1.5" style="margin:0 auto;"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                <p class="image-upload__text">Click to upload images (automatically compressed for fast loading)</p>
            </div>
            <input type="file" id="imageInput" name="images" multiple accept="image/*" style="display:none;" onchange="previewImages(this)">
            <div id="imagePreview" class="image-upload__preview"></div>
        </div>

        <!-- Product Video Upload -->
        <div class="form-group">
            <label class="form-label">Product Video (MP4, WebM)</label>
            {% if product and product.video %}
            <div class="mb-3">
                <p class="text-xs text-muted mb-2">Current Video:</p>
                <video controls style="max-width:100%;max-height:240px;border-radius:var(--radius-md);" preload="metadata">
                    <source src="{{ product.video.url }}">
                    Your browser does not support video playback.
                </video>
            </div>
            {% endif %}
            <input type="file" name="video" class="form-input" accept="video/mp4,video/webm" onchange="previewVideo(this)">
            <span class="form-hint">Optional 1-minute demo video. Played with interactive HTML5 video controls.</span>
            <div id="videoPreview" class="mt-3"></div>
        </div>

        <div class="flex gap-3 mt-6">
            <button type="submit" class="btn btn--primary">{% if editing %}Save Changes{% else %}Add Product{% endif %}</button>
            <a href="{% url 'dashboard:product_list' %}" class="btn btn--secondary">Cancel</a>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_js %}
<script>
function previewImages(input) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    Array.from(input.files).slice(0, 3).forEach(file => {
        const reader = new FileReader();
        reader.onload = e => {
            const img = document.createElement('img');
            img.src = e.target.result;
            img.className = 'image-upload__thumb';
            preview.appendChild(img);
        };
        reader.readAsDataURL(file);
    });
}

function previewVideo(input) {
    const container = document.getElementById('videoPreview');
    container.innerHTML = '';
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const video = document.createElement('video');
        video.controls = true;
        video.style.maxWidth = '100%';
        video.style.maxHeight = '240px';
        video.style.borderRadius = 'var(--radius-md)';
        video.src = URL.createObjectURL(file);
        container.appendChild(video);
    }
}

function deleteImage(imageId) {
    if (!confirm('Delete this image?')) return;
    fetch('/dashboard/products/images/' + imageId + '/delete/', {
        method: 'POST',
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
    }).then(r => r.json()).then(d => {
        if (d.success) location.reload();
    });
}
</script>
{% endblock %}
