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

{% block page_title %}Create New Flash Sale{% endblock %}
{% block header_actions %}
<a href="{% url 'dashboard:sale_list' %}" class="btn btn--secondary btn--sm">Back to Sales</a>
{% endblock %}

{% block dashboard_content %}
{% if error %}
<div class="alert alert--error mb-6" style="background:#FEE2E2; color:#991B1B; padding:var(--space-4); border-radius:var(--radius-md); border:1px solid #FCA5A5;">
    <strong>Error:</strong> {{ error }}
</div>
{% endif %}

<form method="POST" action="{% url 'dashboard:sale_create' %}" id="sale-create-form">
    {% csrf_token %}

    <!-- 1. General Details -->
    <div class="dash-card mb-6">
        <div class="dash-card__header">
            <h3 class="dash-card__title">1. Sale Details & Pricing Model</h3>
        </div>
        <div class="dash-card__body">
            <div class="form-group mb-4">
                <label class="form-label" for="title">Sale Title *</label>
                <input type="text" id="title" name="title" class="form-input" placeholder="e.g. Weekend Tech Mega Clearance" required value="{{ request.POST.title }}">
                <span class="form-help text-xs text-muted mt-1" style="display:block;">This title will be featured prominently on your public sale landing page.</span>
            </div>

            <div class="grid grid--2 gap-4 mb-4">
                <div class="form-group">
                    <label class="form-label">Pricing Model *</label>
                    <div style="display:flex; flex-direction:column; gap:var(--space-3); margin-top:var(--space-2);">
                        <label class="card card--flat" style="display:flex; align-items:flex-start; gap:var(--space-3); cursor:pointer; padding:var(--space-4);">
                            <input type="radio" name="pricing_model" value="daily_rate" checked style="margin-top:3px;">
                            <div>
                                <strong>Daily Booking Rate</strong>
                                <p class="text-xs text-muted mt-1">Pay an upfront daily rate to host your flash sale window.</p>
                            </div>
                        </label>
                        <label class="card card--flat" style="display:flex; align-items:flex-start; gap:var(--space-3); cursor:pointer; padding:var(--space-4);">
                            <input type="radio" name="pricing_model" value="commission" style="margin-top:3px;">
                            <div>
                                <strong>Commission Based (5% After Sale)</strong>
                                <p class="text-xs text-muted mt-1">Flat GHS 10 booking deposit + 5% commission deducted after sale completes.</p>
                            </div>
                        </label>
                    </div>
                </div>

                <div>
                    <div class="form-group mb-3">
                        <label class="form-label">Start Date & Time *</label>
                        <div class="flex gap-2">
                            <input type="date" name="start_date" class="form-input" required value="{{ request.POST.start_date }}">
                            <input type="time" name="start_time" class="form-input" value="00:00" style="max-width:110px;">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">End Date & Time *</label>
                        <div class="flex gap-2">
                            <input type="date" name="end_date" class="form-input" required value="{{ request.POST.end_date }}">
                            <input type="time" name="end_time" class="form-input" value="23:59" style="max-width:110px;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 2. Select Products for Sale -->
    <div class="dash-card mb-6">
        <div class="dash-card__header">
            <h3 class="dash-card__title">2. Select & Price Products for This Sale</h3>
        </div>
        <div class="dash-card__body">
            {% if products %}
            <p class="text-sm text-muted mb-4">Check the products you wish to include, set their flash sale price, discount percentage (optional), and allocated sale inventory stock.</p>
            <div class="flex flex-col gap-4">
                {% for product in products %}
                <div class="card card--flat product-select-row" data-base-price="{{ product.base_price }}" style="padding:var(--space-4);">
                    <div class="flex items-center gap-3 mb-3 flex-wrap">
                        <input type="checkbox" name="product_ids" value="{{ product.id }}" id="prod_{{ product.id }}" class="prod-checkbox" style="width:20px; height:20px; cursor:pointer;">
                        {% if product.primary_image %}
                        <img src="{{ product.primary_image.image.url }}" alt="" style="width:48px; height:48px; border-radius:var(--radius-sm); object-fit:cover;">
                        {% else %}
                        <div style="width:48px; height:48px; border-radius:var(--radius-sm); background:var(--color-border-light); display:flex; align-items:center; justify-content:center; color:var(--color-text-muted); font-size:10px;">No img</div>
                        {% endif %}
                        <div style="flex:1;">
                            <label for="prod_{{ product.id }}" style="font-weight:700; cursor:pointer; font-size:var(--font-size-base);">{{ product.name }}</label>
                            <span class="text-xs text-muted" style="display:block;">Base Price: GHS {{ product.base_price|floatformat:2 }}</span>
                        </div>
                    </div>

                    <div class="grid grid--3 gap-3 pt-3" style="border-top:1px solid var(--color-border-light);">
                        <div>
                            <label class="text-xs form-label" for="price_{{ product.id }}">Sale Price (GHS) *</label>
                            <input type="number" step="0.01" min="0.01" name="price_{{ product.id }}" id="price_{{ product.id }}" class="form-input text-sm sale-price-input" value="{{ product.base_price }}">
                        </div>
                        <div>
                            <label class="text-xs form-label" for="discount_{{ product.id }}">Discount (% OFF)</label>
                            <input type="number" step="0.1" min="0" max="99" name="discount_{{ product.id }}" id="discount_{{ product.id }}" class="form-input text-sm sale-discount-input" placeholder="e.g. 15">
                        </div>
                        <div>
                            <label class="text-xs form-label" for="stock_{{ product.id }}">Sale Stock Pool *</label>
                            <input type="number" min="1" name="stock_{{ product.id }}" class="form-input text-sm" value="10">
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
            {% else %}
            <div class="empty-state">
                <h4 class="empty-state__title">No Active Products Found</h4>
                <p class="empty-state__desc">You need at least one active product in your catalog before creating a sale.</p>
                <a href="{% url 'dashboard:product_create' %}" class="btn btn--primary btn--sm mt-3">Add Product First</a>
            </div>
            {% endif %}
        </div>
    </div>

    {% if products %}
    <div class="flex justify-end gap-3 mb-8">
        <a href="{% url 'dashboard:sale_list' %}" class="btn btn--secondary">Cancel</a>
        <button type="submit" class="btn btn--primary btn--lg">Proceed to Booking Payment &rarr;</button>
    </div>
    {% endif %}
</form>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.product-select-row').forEach(row => {
        const basePrice = parseFloat(row.getAttribute('data-base-price')) || 0;
        const priceInput = row.querySelector('.sale-price-input');
        const discountInput = row.querySelector('.sale-discount-input');

        if (!priceInput || !discountInput || basePrice <= 0) return;

        let isUpdating = false;

        // Auto-calculate Discount % when Sale Price changes
        priceInput.addEventListener('input', function() {
            if (isUpdating) return;
            isUpdating = true;
            const salePrice = parseFloat(this.value);
            if (!isNaN(salePrice) && salePrice > 0 && salePrice < basePrice) {
                const discountPct = ((basePrice - salePrice) / basePrice) * 100;
                discountInput.value = discountPct.toFixed(1).replace(/\.0$/, '');
            } else {
                discountInput.value = '';
            }
            isUpdating = false;
        });

        // Auto-calculate Sale Price when Discount % changes
        discountInput.addEventListener('input', function() {
            if (isUpdating) return;
            isUpdating = true;
            const discountPct = parseFloat(this.value);
            if (!isNaN(discountPct) && discountPct >= 0 && discountPct < 100) {
                const calculatedSalePrice = basePrice * (1 - (discountPct / 100));
                priceInput.value = calculatedSalePrice.toFixed(2);
            } else if (this.value === '' || discountPct === 0) {
                priceInput.value = basePrice.toFixed(2);
            }
            isUpdating = false;
        });
    });
});
</script>
{% endblock %}
