{% extends "indy_hub/base.html" %}
{% load i18n %}
{% load static %}
{% load humanize %}
{% load tz %}

{% block page_title %}{% trans "Buy Materials from Hub" %}{% endblock page_title %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'indy_hub/css/page_headers.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/blueprints.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/material_exchange.css' %}">
{% endblock extra_css %}

{% block content %}
<div class="container-fluid py-4">
    <div class="page-header mb-4">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                <div>
                    <h2 class="h3 mb-1">
                        <i class="fas fa-shopping-cart me-2"></i>
                        {% trans "Buy Materials from Hub" %}
                    </h2>
                    <p class="description">{% trans "Purchase materials from corp stock" %}</p>
                </div>
                <div class="d-flex gap-2">
                    <a href="{% url 'indy_hub:material_exchange_index' %}" class="btn btn-outline-light">
                        <i class="fas fa-arrow-left me-1"></i>{% trans "Back to Hub" %}
                    </a>
                </div>
            </div>
            <i class="fas fa-shopping-cart header-bg"></i>
        </div>

        <div class="glass-panel p-4 mb-4">
            <div class="d-flex align-items-start gap-3">
                <i class="fas fa-info-circle text-info mt-1 info-icon-fixed"></i>
                <div class="info-body-flex">
                    <p class="mb-2 small text-muted text-uppercase">{% trans "Pricing Formula" %}</p>
                    <div class="d-flex align-items-baseline gap-2 flex-wrap">
                        <span class="fw-semibold">
                            {% if config.buy_markup_base == 'sell' %}
                                {% trans "Jita Sell Price" %}
                            {% else %}
                                {% trans "Jita Buy Price" %}
                            {% endif %}
                        </span>
                        {% if config.buy_markup_percent > 0 %}
                        <span class="text-success">+</span>
                        <span class="text-success fw-bold h5 mb-0">{{ config.buy_markup_percent }}%</span>
                        {% elif config.buy_markup_percent < 0 %}
                        <span class="text-success fw-bold h5 mb-0">{{ config.buy_markup_percent }}%</span>
                        {% else %}
                        <span class="text-muted small">({% trans "no markup" %})</span>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% if corp_assets_scope_missing %}
            <div class="alert alert-danger mt-3 mb-0">
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                    <div>
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        {% trans "Missing corporation assets token: the hub cannot load stock. A director must authorize the required ESI scope for the corporation." %}
                    </div>
                    <div class="d-flex gap-2">
                        <a class="btn btn-outline-light btn-sm" href="{% url 'indy_hub:esi_hub' %}">{% trans "Open ESI" %}</a>
                        <a class="btn btn-outline-light btn-sm" href="{% url 'indy_hub:token_management' %}">{% trans "Manage tokens" %}</a>
                    </div>
                </div>
            </div>
            {% endif %}
            {% if stock_refreshing %}
            <div class="alert alert-info mt-3 mb-0">
                <i class="fas fa-sync fa-spin me-2"></i>
                {% trans "Refreshing via ESI (assets + prices)." %}
            </div>
            {% endif %}
        </div>

        {% if stock %}
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="glass-panel p-4">
                    <h5 class="mb-4">
                        {% trans "Available Stock in" %} {{ config.structure_name }} - {{ hangar_division_label }} hangar division
                    </h5>
                        <div class="text-muted small">
                            {% trans "Last update" %}:
                            {% if buy_last_update %}
                                {{ buy_last_update|timezone:"UTC"|date:"Y-m-d H:i" }} EVE
                            {% else %}
                                {% trans "Never" %}
                            {% endif %}
                        </div>
                    <form method="post" id="purchaseForm">
                        {% csrf_token %}
                        <input type="hidden" id="hidden_order_reference" name="order_reference" value="">
                        <div class="table-responsive">
                            <table class="table table-hover stock-table align-middle">
                                <thead>
                                    <tr>
                                        <th class="stock-col-icon"></th>
                                        <th>{% trans "Item" %}</th>
                                        <th class="text-end">{% trans "Stock" %}</th>
                                        <th class="text-end">{% trans "Unit Price" %}</th>
                                        <th class="text-center stock-col-qty">{% trans "Quantity" %}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for item in stock %}
                                    <tr class="stock-row"
                                        data-type-id="{{ item.type_id }}"
                                        data-type-name="{{ item.type_name }}"
                                        data-unit-price="{{ item.sell_price_to_member }}"
                                        data-max-qty="{{ item.quantity }}">
                                        <td>
                                            <img
                                                src="https://images.evetech.net/types/{{ item.type_id }}/icon?size=64"
                                                alt="{{ item.type_name }}"
                                                class="item-icon">
                                        </td>
                                        <td>
                                            <strong>{{ item.type_name }}</strong>
                                        </td>
                                        <td class="text-end">
                                            <span class="badge bg-primary">{{ item.quantity|intcomma }}</span>
                                        </td>
                                        <td class="text-end text-primary fw-semibold">
                                            {{ item.sell_price_to_member|floatformat:2|intcomma }} ISK
                                        </td>
                                        <td class="text-center">
                                            <div>
                                                <input
                                                    type="number"
                                                    name="qty_{{ item.type_id }}"
                                                    id="qty-{{ item.type_id }}"
                                                    class="form-control qty-input"
                                                    min="0"
                                                    max="{{ item.quantity }}"
                                                    value="0"
                                                    data-type-id="{{ item.type_id }}"
                                                    data-max="{{ item.quantity }}">
                                                <div class="qty-error" id="error-{{ item.type_id }}">
                                                    {% trans "Max:" %} {{ item.quantity|intcomma }}
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="invoice-panel">
                    <div class="glass-panel p-4">
                        <h5 class="mb-3">
                            <i class="fas fa-receipt me-2"></i>{% trans "Order Summary" %}
                        </h5>
                        <div id="invoiceContent">
                            <div class="empty-invoice">
                                <i class="fas fa-shopping-cart fa-3x mb-3 opacity-25"></i>
                                <p class="mb-0">{% trans "Select items to see your order summary" %}</p>
                            </div>
                        </div>
                        <div id="invoiceItems" class="d-none">
                            <div id="itemsList"></div>
                            <div class="invoice-total">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="fw-bold">{% trans "Total Amount" %}</span>
                                    <span class="h4 mb-0 text-primary" id="totalAmount">0 ISK</span>
                                </div>
                                <button type="submit" form="purchaseForm" class="btn btn-primary w-100 mt-3">
                                    <i class="fas fa-shopping-cart me-2"></i>{% trans "Confirm Purchase" %}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% else %}
        <div class="glass-panel p-4">
            <div class="alert alert-warning mb-3">
                <i class="fas fa-exclamation-triangle me-2"></i>
                {% trans "No materials currently available in stock. Please check back later." %}
            </div>
            {% if perms.indy_hub.can_manage_material_hub %}
            <div class="d-flex gap-2">
                <form method="post" action="{% url 'indy_hub:material_exchange_sync_stock' %}" class="d-inline">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-info">
                        <i class="fas fa-sync me-1"></i>{% trans "Sync Stock from ESI" %}
                    </button>
                </form>
                <form method="post" action="{% url 'indy_hub:material_exchange_sync_prices' %}" class="d-inline">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-secondary">
                        <i class="fas fa-dollar-sign me-1"></i>{% trans "Sync Jita Prices" %}
                    </button>
                </form>
            </div>
            {% endif %}
        </div>
        {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const qtyInputs = document.querySelectorAll('.qty-input');

    function formatNumber(num) {
        return new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(num);
    }

    function checkQuantityLimit(input) {
        const qty = parseInt(input.value) || 0;
        const max = parseInt(input.dataset.max);
        const typeId = input.dataset.typeId;
        const errorDiv = document.getElementById('error-' + typeId);

        if (qty > max) {
            input.classList.add('is-invalid');
            if (errorDiv) {
                errorDiv.style.display = 'block';
            }
            return false;
        } else {
            input.classList.remove('is-invalid');
            if (errorDiv) {
                errorDiv.style.display = 'none';
            }
            return true;
        }
    }

    function updateInvoice() {
        const selectedItems = [];
        let total = 0;

        qtyInputs.forEach(input => {
            const qty = parseInt(input.value) || 0;
            const row = input.closest('tr');

            // Check limit but don't auto-correct during typing
            checkQuantityLimit(input);

            if (qty > 0) {
                const typeId = input.dataset.typeId;
                const typeName = row.dataset.typeName;
                const unitPrice = parseFloat(row.dataset.unitPrice);
                const max = parseInt(input.dataset.max);

                // Use actual qty or max, whichever is lower for calculation
                const effectiveQty = Math.min(qty, max);
                const subtotal = unitPrice * effectiveQty;

                selectedItems.push({
                    name: typeName,
                    qty: effectiveQty,
                    unitPrice: unitPrice,
                    subtotal: subtotal
                });

                total += subtotal;
                row.classList.add('selected');
            } else {
                row.classList.remove('selected');
            }
        });

        const emptyInvoice = document.getElementById('invoiceContent');
        const invoiceItems = document.getElementById('invoiceItems');
        const itemsList = document.getElementById('itemsList');
        const totalAmount = document.getElementById('totalAmount');

        // Guard against missing invoice elements when stock is empty
        if (!emptyInvoice || !invoiceItems) {
            return;
        }

        if (selectedItems.length === 0) {
            emptyInvoice.classList.remove('d-none');
            invoiceItems.classList.add('d-none');
        } else {
            emptyInvoice.classList.add('d-none');
            invoiceItems.classList.remove('d-none');

            let itemsHTML = '';
            selectedItems.forEach(item => {
                itemsHTML += `
                    <div class="invoice-item">
                        <div class="d-flex justify-content-between mb-1">
                            <strong>${item.name}</strong>
                            <span class="text-primary fw-semibold">${formatNumber(item.subtotal)} ISK</span>
                        </div>
                        <div class="d-flex justify-content-between small text-muted">
                            <span>${item.qty.toLocaleString()} × ${formatNumber(item.unitPrice)} ISK</span>
                        </div>
                    </div>
                `;
            });

            if (itemsList) {
                itemsList.innerHTML = itemsHTML;
            }
            if (totalAmount) {
                totalAmount.textContent = formatNumber(total) + ' ISK';
            }
        }
    }

    qtyInputs.forEach(input => {
        input.addEventListener('input', function() {
            updateInvoice();
        });

        input.addEventListener('blur', function() {
            // Auto-correct on blur
            const qty = parseInt(this.value) || 0;
            const max = parseInt(this.dataset.max);
            if (qty > max) {
                this.value = max;
                updateInvoice();
            }
        });
    });

    // Prevent form submission if any quantity exceeds stock
    const purchaseForm = document.getElementById('purchaseForm');
    if (purchaseForm) {
        purchaseForm.addEventListener('submit', function(e) {
            // Generate order reference and add to form before submitting
            const orderRef = generateOrderReference();
            document.getElementById('hidden_order_reference').value = orderRef;

            let hasError = false;
            qtyInputs.forEach(input => {
                const qty = parseInt(input.value) || 0;
                const max = parseInt(input.dataset.max);
                if (qty > max) {
                    hasError = true;
                    input.value = max; // Auto-correct
                }
            });

            if (hasError) {
                e.preventDefault();
                alert('{% trans "Some quantities exceeded available stock and have been adjusted." %}');
                updateInvoice();
                return false;
            }
        });
    }

    // Generate order reference (same format as server-side)
    function generateOrderReference() {
        const min = 1000000000;
        const max = 9999999999;
        const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
        return `INDY-${randomNum}`;
    }

    // Initial update
    updateInvoice();

    // Live stock refresh progress
    {% if stock_refreshing %}
    const statusUrl = '{% url "indy_hub:material_exchange_buy_stock_refresh_status" %}';
    console.log('Stock polling enabled. Current stock_refreshing:', {{ stock_refreshing|lower }});

    async function pollStockProgress() {
        try {
            const resp = await fetch(statusUrl, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            if (!resp.ok) {
                return;
            }
            const data = await resp.json();
            console.log('Poll status response:', data);

            if (data.running) {
                console.log('Task still running, will poll again in 1s');
                setTimeout(pollStockProgress, 1000);
                return;
            }

            // When finished successfully, reload to show updated stock
            if (data.finished && !data.error) {
                console.log('Stock refresh finished successfully! Reloading page with refreshed=1');
                const url = new URL(window.location.href);
                if (url.searchParams.get('refreshed') !== '1') {
                    url.searchParams.set('refreshed', '1');
                    setTimeout(() => window.location.replace(url.toString()), 300);
                }
            } else {
                console.log('Task finished with error:', data.error);
            }
        } catch (e) {
            console.error('Poll error:', e);
        }
    }

    pollStockProgress();
    {% else %}
    console.log('Stock polling DISABLED - stock_refreshing is False');
    {% endif %}
});
</script>
{% endblock content %}
