{% extends "fortunaisk/base.html" %}
{% load i18n static my_filters %}

{% block page_title %}
    {% trans "Create Automatic Lottery" %}
{% endblock page_title %}

{% block details %}
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <!-- Main Card -->
            <div class="card shadow-lg">
                <!-- Header -->
                <div class="card-header bg-success text-white">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-sync fa-2x me-3"></i>
                        <div>
                            <h4 class="mb-0">{% trans "Create Automatic Lottery" %}</h4>
                            <small class="opacity-75">
                                {% trans "Configure a recurring lottery that runs automatically" %}
                            </small>
                        </div>
                    </div>
                </div>
                <!-- Body -->
                <div class="card-body">
                    <form method="post" id="autoLotteryForm" class="needs-validation" novalidate>
                        {% csrf_token %}

                        <!-- 1. Basic Information -->
                        <div class="mb-4">
                            <h5><i class="fas fa-info-circle text-primary me-2"></i>{% trans "Basic Information" %}</h5>
                            <div class="row g-3">
                                <!-- Lottery Name -->
                                <div class="col-md-6">
                                    <label for="{{ form.name.id_for_label }}" class="form-label">
                                        {% trans "Lottery Name" %}*
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-tag"></i>
                                        </span>
                                        {{ form.name }}
                                    </div>
                                    {% if form.name.errors %}
                                        <div class="text-danger mt-1">{{ form.name.errors|striptags }}</div>
                                    {% endif %}
                                </div>
                                <!-- Frequency -->
                                <div class="col-md-6">
                                    <label class="form-label">{% trans "Frequency" %}*</label>
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-clock"></i>
                                        </span>
                                        {{ form.frequency }}
                                        {{ form.frequency_unit }}
                                    </div>
                                    {% if form.frequency.errors %}
                                        <div class="text-danger mt-1">{{ form.frequency.errors|striptags }}</div>
                                    {% endif %}
                                </div>
                                <!-- Ticket Price -->
                                <div class="col-md-6">
                                    <label for="{{ form.ticket_price.id_for_label }}" class="form-label">
                                        {% trans "Ticket Price (ISK)" %}*
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-coins"></i>
                                        </span>
                                        {{ form.ticket_price }}
                                        <span class="input-group-text">ISK</span>
                                    </div>
                                    {% if form.ticket_price.errors %}
                                        <div class="text-danger mt-1">{{ form.ticket_price.errors|striptags }}</div>
                                    {% endif %}
                                </div>
                                <!-- Duration -->
                                <div class="col-md-6">
                                    <label for="{{ form.duration_value.id_for_label }}" class="form-label">
                                        {% trans "Duration" %}*
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-hourglass-half"></i>
                                        </span>
                                        {{ form.duration_value }}
                                        {{ form.duration_unit }}
                                    </div>
                                    {% if form.duration_value.errors %}
                                        <div class="text-danger mt-1">{{ form.duration_value.errors|striptags }}</div>
                                    {% endif %}
                                    {% if form.duration_unit.errors %}
                                        <div class="text-danger mt-1">{{ form.duration_unit.errors|striptags }}</div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <!-- 2. Winners Configuration -->
                        <div class="mb-4">
                            <h5><i class="fas fa-trophy text-warning me-2"></i>{% trans "Winners Configuration" %}</h5>
                            <div class="row g-3">
                                <!-- Payment Receiver -->
                                <div class="col-md-6">
                                    <label for="{{ form.payment_receiver.id_for_label }}" class="form-label">
                                        {% trans "Payment Receiver" %}
                                    </label>

                                    <!-- Local search field to filter the select -->
                                    <input type="text" class="form-control mb-2" id="paymentReceiverSearch"
                                            placeholder="{% trans 'Filter Corporation...' %}">

                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-user"></i>
                                        </span>
                                        {{ form.payment_receiver }}
                                    </div>
                                    {% if form.payment_receiver.errors %}
                                        <div class="text-danger mt-1">{{ form.payment_receiver.errors|striptags }}</div>
                                    {% endif %}
                                </div>
                                <!-- Number of Winners -->
                                <div class="col-md-6">
                                    <label for="{{ form.winner_count.id_for_label }}" class="form-label">
                                        {% trans "Number of Winners" %}*
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-users"></i>
                                        </span>
                                        {{ form.winner_count }}
                                    </div>
                                    {% if form.winner_count.errors %}
                                        <div class="text-danger mt-1">{{ form.winner_count.errors|striptags }}</div>
                                    {% endif %}
                                </div>
                                <!-- Prize Distribution -->
                                <div class="col-12">
                                    <label class="form-label">
                                        {% trans "Prize Distribution" %}
                                    </label>
                                    <div id="prize-distribution-container">
                                        <!-- Dynamically injected fields via JavaScript -->
                                        {% for idx in distribution_range %}
                                            <div class="input-group mb-2">
                                                <span class="input-group-text">
                                                    {% trans "Winner" %} {{ idx|add:"1" }}
                                                </span>
                                                <input
                                                    type="number"
                                                    name="winners_distribution_entry"
                                                    class="form-control prize-distribution"
                                                    value="{{ form.instance.winners_distribution|index:idx|default_if_none:0 }}"
                                                    min="0"
                                                    max="100"
                                                    step="1"
                                                    required
                                                >
                                                <span class="input-group-text">%</span>
                                            </div>
                                        {% endfor %}
                                    </div>
                                    <!-- Hidden field to store the final distribution -->
                                    {{ form.winners_distribution }}
                                    {% if form.winners_distribution.errors %}
                                        <div class="text-danger mt-1">
                                            {{ form.winners_distribution.errors|striptags }}
                                        </div>
                                    {% endif %}
                                </div>
                            </div>
                        </div>

                        <!-- 3. Additional Settings -->
                        <div class="mb-4">
                            <h5><i class="fas fa-cog text-secondary me-2"></i>{% trans "Additional Settings" %}</h5>
                            <div class="row g-3">
                                <!-- Max Tickets per User -->
                                <div class="col-md-6">
                                    <label for="{{ form.max_tickets_per_user.id_for_label }}" class="form-label">
                                        {% trans "Max Tickets per User" %}
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">
                                            <i class="fas fa-ticket-alt"></i>
                                        </span>
                                        {{ form.max_tickets_per_user }}
                                    </div>
                                    {% if form.max_tickets_per_user.errors %}
                                        <div class="text-danger mt-1">
                                            {{ form.max_tickets_per_user.errors|striptags }}
                                        </div>
                                    {% endif %}
                                    <div class="form-text">
                                        {% trans "Leave blank for unlimited tickets." %}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="d-flex justify-content-between align-items-center mt-4">
                            <a href="{% url 'fortunaisk:admin_dashboard' %}" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>
                                {% trans "Back" %}
                            </a>
                            <button
                                type="submit"
                                class="btn btn-lg btn-primary"
                            >
                                <i class="fas fa-plus me-2"></i>
                                {% trans "Create Automatic Lottery" %}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- JavaScript for distribution & local filter -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 1) Local filtering for Payment Receiver
    const searchInput = document.getElementById("paymentReceiverSearch");
    const selectElem = document.getElementById("id_payment_receiver");
    if (searchInput && selectElem) {
        searchInput.addEventListener("keyup", function() {
            const filter = this.value.toLowerCase().trim();
            const options = selectElem.querySelectorAll("option");
            options.forEach(opt => {
                const text = opt.textContent.toLowerCase();
                if (text.includes(filter) || opt.value === "") {
                    opt.style.display = "";
                } else {
                    opt.style.display = "none";
                }
            });
        });
    }

    // 2) Prize Distribution logic
    const FORM_ELEMENTS = {
        form: document.getElementById('autoLotteryForm'),
        winnerCount: document.getElementById('id_winner_count'),
        distributionContainer: document.getElementById('prize-distribution-container'),
        distributionInputs: () => document.querySelectorAll('.prize-distribution'),
        hiddenDistributionInput: document.getElementById('id_winners_distribution'),
    };

    const ERROR_MESSAGES = {
        distribution: 'The sum of percentages must be equal to 100.',
        required: 'This field is required.',
        range: 'Please enter a value between 0 and 100.',
    };

    class FormValidator {
        static validateDistribution(distributions) {
            const values = Array.from(distributions)
                .map(input => parseInt(input.value.trim(), 10))
                .filter(val => !isNaN(val));
            const total = values.reduce((a, b) => a + b, 0);
            return total === 100;
        }

        static showError(element, message) {
            element.classList.add('is-invalid');
            if (!element.nextElementSibling?.classList.contains('invalid-feedback')) {
                const feedback = document.createElement('div');
                feedback.className = 'invalid-feedback';
                feedback.textContent = message;
                element.parentNode.appendChild(feedback);
            }
        }

        static removeError(element) {
            element.classList.remove('is-invalid');
            const feedback = element.nextElementSibling;
            if (feedback?.classList.contains('invalid-feedback')) {
                feedback.remove();
            }
        }
    }

    class PrizeDistributionHandler {
        static createDistributionField(index, value = 100) {
            const div = document.createElement('div');
            div.className = 'input-group mb-2';

            const prepend = document.createElement('span');
            prepend.className = 'input-group-text';
            prepend.textContent = `Winner ${index + 1}`;

            const input = document.createElement('input');
            input.type = 'number';
            input.min = '0';
            input.max = '100';
            input.step = '1';
            input.className = 'form-control prize-distribution';
            input.value = value;
            input.required = true;

            const append = document.createElement('span');
            append.className = 'input-group-text';
            append.textContent = '%';

            div.appendChild(prepend);
            div.appendChild(input);
            div.appendChild(append);

            return div;
        }

        static updateDistributionFields(count) {
            const container = FORM_ELEMENTS.distributionContainer;
            container.innerHTML = '';

            let remaining = 100;
            for (let i = 0; i < count; i++) {
                let value;
                if (count === 1) {
                    value = 100;
                } else {
                    if (i === count - 1) {
                        value = remaining;
                    } else {
                        value = Math.floor(100 / count);
                        remaining -= value;
                    }
                }
                const field = this.createDistributionField(i, value);
                container.appendChild(field);
            }

            this.updateHiddenDistribution();
            this.addInputListeners();
        }

        static updateHiddenDistribution() {
            const distributionElems = FORM_ELEMENTS.distributionInputs();
            const distributionValues = Array.from(distributionElems)
                .map(input => parseInt(input.value.trim(), 10))
                .filter(val => !isNaN(val));
            const distributionStr = JSON.stringify(distributionValues);
            FORM_ELEMENTS.hiddenDistributionInput.value = distributionStr;
            console.log('Cleaned winners distribution:', distributionStr);
        }

        static addInputListeners() {
            const distributionElems = FORM_ELEMENTS.distributionInputs();
            distributionElems.forEach(input => {
                input.addEventListener('input', () => {
                    FormValidator.removeError(input);
                    PrizeDistributionHandler.updateHiddenDistribution();
                });
            });
        }
    }

    class PriceFormatter {
        static handleBlur(event) {
            const input = event.target;
            if (input.value) {
                input.value = parseInt(input.value, 10).toFixed(0);
            }
        }
    }

    function initializeEventListeners() {
        // Update distribution fields on winnerCount change
        FORM_ELEMENTS.winnerCount?.addEventListener('input', function(e) {
            const count = parseInt(e.target.value, 10);
            if (!isNaN(count) && count > 0) {
                PrizeDistributionHandler.updateDistributionFields(count);
            } else {
                FORM_ELEMENTS.distributionContainer.innerHTML = '';
                FORM_ELEMENTS.hiddenDistributionInput.value = '';
            }
        });

        // Initialize distribution fields on page load
        const initialCount = parseInt(FORM_ELEMENTS.winnerCount?.value, 10) || 1;
        PrizeDistributionHandler.updateDistributionFields(initialCount);

        // Format ticket price on blur
        const priceInput = document.getElementById('id_ticket_price');
        priceInput?.addEventListener('blur', PriceFormatter.handleBlur);

        // Validate form on submit
        FORM_ELEMENTS.form?.addEventListener('submit', function(event) {
            let isValid = true;

            const distributionElems = FORM_ELEMENTS.distributionInputs();
            const distributionValues = [];

            distributionElems.forEach(input => {
                const value = parseInt(input.value.trim(), 10);
                if (isNaN(value) || value < 0 || value > 100) {
                    FormValidator.showError(input, ERROR_MESSAGES.range);
                    isValid = false;
                } else {
                    FormValidator.removeError(input);
                    distributionValues.push(value);
                }
            });

            const total = distributionValues.reduce((a, b) => a + b, 0);
            if (total !== 100) {
                alert(ERROR_MESSAGES.distribution);
                isValid = false;
                distributionElems.forEach(input => {
                    FormValidator.showError(input, ERROR_MESSAGES.distribution);
                });
            }

            if (!isValid) {
                event.preventDefault();
                event.stopPropagation();
            } else {
                PrizeDistributionHandler.updateHiddenDistribution();
                console.log('Final winners distribution:', FORM_ELEMENTS.hiddenDistributionInput.value);
            }
        });
    }

    initializeEventListeners();
});
</script>
{% endblock details %}
