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

{% block title %}Add Product{% endblock %}

{% block extra_head %}
<style>
.crop-wrapper {
    max-height: 500px;
    overflow: hidden;
    background: #000;
}

.crop-wrapper img {
    max-width: 100%;
    display: block;
}

.crop-controls {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
}

.image-upload-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border: 2px dashed #dee2e6;
}

#image-crop-container {
    border: 2px solid #D4AF37;
    border-radius: 8px;
    padding: 15px;
    background: #fff;
}
</style>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Add Product</h1>
    <a href="{{ url_for('admin_products') }}" class="btn btn-outline-secondary">
        <i class="fas fa-arrow-left me-2"></i>Back to Products
    </a>
</div>

<div class="row">
    <div class="col-lg-8">
        <div class="card shadow">
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    {{ form.hidden_tag() }}
                    
                    <div class="mb-3">
                        {{ form.name.label(class="form-label fw-bold") }}
                        {{ form.name(class="form-control", placeholder="Enter product name (e.g., Men's Track Suit - Black)") }}
                        {% if form.name.errors %}
                            <div class="text-danger">
                                {% for error in form.name.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                        <small class="text-muted">Use a descriptive name that includes category, color, and key features.</small>
                    </div>
                    
                    <div class="mb-3">
                        {{ form.description.label(class="form-label") }}
                        {{ form.description(class="form-control", rows="4") }}
                        {% if form.description.errors %}
                            <div class="text-danger">
                                {% for error in form.description.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                {{ form.price.label(class="form-label") }}
                                {{ form.price(class="form-control") }}
                                {% if form.price.errors %}
                                    <div class="text-danger">
                                        {% for error in form.price.errors %}
                                            <small>{{ error }}</small>
                                        {% endfor %}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                {{ form.stock_quantity.label(class="form-label") }}
                                {{ form.stock_quantity(class="form-control") }}
                                {% if form.stock_quantity.errors %}
                                    <div class="text-danger">
                                        {% for error in form.stock_quantity.errors %}
                                            <small>{{ error }}</small>
                                        {% endfor %}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                {{ form.category_id.label(class="form-label") }}
                                {{ form.category_id(class="form-select") }}
                                {% if form.category_id.errors %}
                                    <div class="text-danger">
                                        {% for error in form.category_id.errors %}
                                            <small>{{ error }}</small>
                                        {% endfor %}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                {{ form.subcategory_id.label(class="form-label") }}
                                {{ form.subcategory_id(class="form-select") }}
                                {% if form.subcategory_id.errors %}
                                    <div class="text-danger">
                                        {% for error in form.subcategory_id.errors %}
                                            <small>{{ error }}</small>
                                        {% endfor %}
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        {{ form.image.label(class="form-label fw-bold") }}
                        <div class="image-upload-section">
                            <input type="file" id="image-upload" class="form-control" accept="image/*" onchange="handleImageUpload(this)">
                            <input type="hidden" name="image" id="cropped-image-data">
                            
                            <div id="image-crop-container" class="mt-3" style="display: none;">
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="crop-wrapper">
                                            <img id="image-to-crop" src="" alt="Image to crop">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="crop-controls">
                                            <h6 class="mb-3">Crop Controls</h6>
                                            <div class="mb-3">
                                                <label class="form-label">Aspect Ratio</label>
                                                <select id="aspect-ratio" class="form-select" onchange="changeAspectRatio()">
                                                    <option value="free">Free</option>
                                                    <option value="1">Square (1:1)</option>
                                                    <option value="1.33">4:3</option>
                                                    <option value="1.78">16:9</option>
                                                    <option value="0.75">3:4</option>
                                                </select>
                                            </div>
                                            <div class="d-grid gap-2">
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="rotateImage(-90)">
                                                    <i class="fas fa-rotate-left me-1"></i>Rotate Left
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="rotateImage(90)">
                                                    <i class="fas fa-rotate-right me-1"></i>Rotate Right
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="flipImage('horizontal')">
                                                    <i class="fas fa-arrows-left-right me-1"></i>Flip Horizontal
                                                </button>
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="flipImage('vertical')">
                                                    <i class="fas fa-arrows-up-down me-1"></i>Flip Vertical
                                                </button>
                                                <button type="button" class="btn btn-success" onclick="cropImage()">
                                                    <i class="fas fa-crop me-1"></i>Apply Crop
                                                </button>
                                                <button type="button" class="btn btn-danger" onclick="resetCrop()">
                                                    <i class="fas fa-times me-1"></i>Reset
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="cropped-preview" class="mt-3" style="display: none;">
                                    <h6>Cropped Preview:</h6>
                                    <img id="preview-image" src="" alt="Cropped preview" style="max-width: 200px; max-height: 200px;">
                                </div>
                            </div>
                        </div>
                        {% if form.image.errors %}
                            <div class="text-danger">
                                {% for error in form.image.errors %}
                                    <small>{{ error }}</small>
                                {% endfor %}
                            </div>
                        {% endif %}
                        <small class="text-muted">Upload an image and crop it to fit perfectly. Recommended size: 800x800px.</small>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check mb-3">
                                {{ form.is_featured(class="form-check-input") }}
                                {{ form.is_featured.label(class="form-check-label") }}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mb-3">
                                {{ form.is_clearance(class="form-check-input") }}
                                {{ form.is_clearance.label(class="form-check-label") }}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Color Variants Section -->
                    <div class="mb-4">
                        <h5 class="mb-3">Color Variants</h5>
                        <div id="color-variants">
                            <div class="color-variant-item border rounded p-3 mb-3">
                                <div class="row">
                                    <div class="col-md-3">
                                        <label class="form-label">Color Name</label>
                                        <input type="text" name="variant_colors[]" class="form-control" placeholder="e.g., White, Black, Red">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Color Code</label>
                                        <input type="color" name="variant_color_codes[]" class="form-control form-control-color" value="#ffffff">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Stock</label>
                                        <input type="number" name="variant_stock[]" class="form-control" value="0" min="0">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Variant Image</label>
                                        <input type="file" name="variant_images[]" class="form-control" accept="image/*">
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Price Adj.</label>
                                        <input type="number" name="variant_price_adjustments[]" class="form-control" value="0" step="0.01" placeholder="0.00">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="addColorVariant()">
                            <i class="fas fa-plus me-1"></i>Add Another Color
                        </button>
                    </div>
                    
                    <button type="submit" class="btn btn-orange">
                        <i class="fas fa-save me-2"></i>Add Product
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
let cropper;
let croppedImageData = null;

document.addEventListener('DOMContentLoaded', function() {
    const categorySelect = document.getElementById('category_id');
    const subcategorySelect = document.getElementById('subcategory_id');
    
    function updateSubcategories() {
        const selectedCategory = categorySelect.value;
        subcategorySelect.innerHTML = '<option value="0">Select Subcategory</option>';
        if (!selectedCategory || selectedCategory == '0') return;
        fetch('/api/subcategories/' + selectedCategory)
            .then(r => r.json())
            .then(data => {
                data.forEach(function(subcat) {
                    const option = document.createElement('option');
                    option.value = subcat.id;
                    option.textContent = subcat.name;
                    subcategorySelect.appendChild(option);
                });
            });
    }

    categorySelect.addEventListener('change', updateSubcategories);
    updateSubcategories();
});

// Image cropping functions
function handleImageUpload(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const imageToCrop = document.getElementById('image-to-crop');
            imageToCrop.src = e.target.result;
            document.getElementById('image-crop-container').style.display = 'block';
            
            if (cropper) {
                cropper.destroy();
            }
            
            cropper = new Cropper(imageToCrop, {
                aspectRatio: NaN,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                restore: false,
                guides: true,
                center: true,
                highlight: true,
                cropBoxMovable: true,
                cropBoxResizable: true,
                toggleDragModeOnDblclick: false,
            });
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function changeAspectRatio() {
    const ratio = document.getElementById('aspect-ratio').value;
    if (cropper) {
        if (ratio === 'free') {
            cropper.setAspectRatio(NaN);
        } else {
            cropper.setAspectRatio(parseFloat(ratio));
        }
    }
}

function rotateImage(degree) {
    if (cropper) {
        cropper.rotate(degree);
    }
}

function flipImage(direction) {
    if (cropper) {
        if (direction === 'horizontal') {
            const data = cropper.getData();
            cropper.scaleX(data.scaleX === 1 ? -1 : 1);
        } else {
            const data = cropper.getData();
            cropper.scaleY(data.scaleY === 1 ? -1 : 1);
        }
    }
}

function cropImage() {
    if (cropper) {
        const canvas = cropper.getCroppedCanvas({
            width: 800,
            height: 800,
            minWidth: 256,
            minHeight: 256,
            maxWidth: 4096,
            maxHeight: 4096,
            fillColor: '#fff',
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high',
        });
        
        croppedImageData = canvas.toDataURL('image/jpeg', 0.9);
        document.getElementById('cropped-image-data').value = croppedImageData;
        
        const previewImage = document.getElementById('preview-image');
        previewImage.src = croppedImageData;
        document.getElementById('cropped-preview').style.display = 'block';
        
        alert('Image cropped successfully! Click "Add Product" to save.');
    }
}

function resetCrop() {
    if (cropper) {
        cropper.reset();
        document.getElementById('cropped-preview').style.display = 'none';
        document.getElementById('cropped-image-data').value = '';
        croppedImageData = null;
    }
}

// Function to add new color variant
function addColorVariant() {
    const colorVariants = document.getElementById('color-variants');
    const variantItem = document.createElement('div');
    variantItem.className = 'color-variant-item border rounded p-3 mb-3';
    variantItem.innerHTML = `
        <div class="row">
            <div class="col-md-3">
                <label class="form-label">Color Name</label>
                <input type="text" name="variant_colors[]" class="form-control" placeholder="e.g., White, Black, Red">
            </div>
            <div class="col-md-2">
                <label class="form-label">Color Code</label>
                <input type="color" name="variant_color_codes[]" class="form-control form-control-color" value="#ffffff">
            </div>
            <div class="col-md-2">
                <label class="form-label">Stock</label>
                <input type="number" name="variant_stock[]" class="form-control" value="0" min="0">
            </div>
            <div class="col-md-3">
                <label class="form-label">Variant Image</label>
                <input type="file" name="variant_images[]" class="form-control" accept="image/*">
            </div>
            <div class="col-md-1">
                <label class="form-label">Price Adj.</label>
                <input type="number" name="variant_price_adjustments[]" class="form-control" value="0" step="0.01" placeholder="0.00">
            </div>
            <div class="col-md-1 d-flex align-items-end">
                <button type="button" class="btn btn-danger btn-sm" onclick="removeColorVariant(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `;
    colorVariants.appendChild(variantItem);
}

function removeColorVariant(button) {
    const variantItem = button.closest('.color-variant-item');
    variantItem.remove();
}
</script>

<style>
.crop-wrapper {
    max-height: 500px;
    overflow: hidden;
}

.crop-wrapper img {
    max-width: 100%;
}

.crop-controls {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
}

.image-upload-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    border: 2px dashed #dee2e6;
}
</style>
{% endblock %}
