{% 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-stretch justify-content-between gap-3">
                <div class="d-flex flex-column h-100">
                    <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 Hub stock" %}</p>
                    <div class="mt-auto">
                        <span class="badge rounded-pill bg-info-subtle text-info border fs-6">
                            <i class="fas fa-tags me-1"></i>{% trans "Pricing Formula" %}:
                            {% if config.buy_markup_base == 'sell' %}
                                {% trans "Jita Sell Price" %}
                            {% else %}
                                {% trans "Jita Buy Price" %}
                            {% endif %}
                            {% if config.buy_markup_percent > 0 %}
                                +{{ config.buy_markup_percent }}%
                            {% elif config.buy_markup_percent < 0 %}
                                {{ config.buy_markup_percent }}%
                            {% else %}
                                ({% trans "no markup" %})
                            {% endif %}
                        </span>
                    </div>
                </div>
                <div class="d-flex gap-2 align-self-start">
                    <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>

        {% if stock_refreshing %}
        <div class="d-flex flex-column align-items-center justify-content-center py-5">
            <svg width="56" height="56" viewBox="0 0 24 24" aria-hidden="true" class="text-info">
                <g stroke="currentColor" fill="none" stroke-width="1" stroke-linecap="round">
                    <circle cx="12" cy="12" r="10">
                        <animate attributeName="stroke-dasharray" dur="1.5s" calcMode="spline" values="0 150;42 150;42 150;42 150" keyTimes="0;0.475;0.95;1" keySplines="0.42,0,0.58,1;0.42,0,0.58,1;0.42,0,0.58,1" repeatCount="indefinite" />
                        <animate attributeName="stroke-dashoffset" dur="1.5s" calcMode="spline" values="0;-16;-59;-59" keyTimes="0;0.475;0.95;1" keySplines="0.42,0,0.58,1;0.42,0,0.58,1;0.42,0,0.58,1" repeatCount="indefinite" />
                    </circle>
                    <animateTransform attributeName="transform" type="rotate" dur="2s" values="0 12 12;360 12 12" repeatCount="indefinite" />
                </g>
            </svg>
            <div class="mt-3 text-muted">{% trans "Refreshing via ESI (assets + prices)." %}</div>
        </div>
        {% endif %}

        <div class="{% if stock_refreshing %}d-none{% endif %}">
            <div class="me-info-bar" role="status">
                <i class="fas fa-clock" aria-hidden="true"></i>
                <div class="me-info-bar-body">
                    <div class="me-info-bar-title">
                        {% trans "Last update" %}:
                        {% if buy_last_update %}
                            {% with buy_utc=buy_last_update|timezone:"UTC" %}
                                {{ buy_utc|date:"Y-m-d H:i" }} EVE
                                <span class="text-muted">
                                    / <span class="js-local-time" data-utc="{{ buy_utc|date:'c' }}">{{ buy_utc|date:"Y-m-d H:i" }}</span> {% trans "Local" %}
                                </span>
                            {% endwith %}
                        {% else %}
                            {% trans "Never" %}
                        {% endif %}
                    </div>
                    <div class="me-info-bar-sub">
                        {% if buy_next_refresh_minutes == 0 %}
                            {% trans "Auto-refresh will run on the next page open." %}
                        {% elif buy_next_refresh_minutes %}
                            {% blocktrans with minutes=buy_next_refresh_minutes %}Auto-refresh runs on page open in about {{ minutes }} minute(s).{% endblocktrans %}
                        {% else %}
                            {% trans "Auto-refresh runs on page open once data is older than 60 minutes." %}
                        {% endif %}
                    </div>
                </div>
            </div>

            <div class="me-instruction-chip" role="status">
                <i class="fas fa-exclamation-circle" aria-hidden="true"></i>
                <div>
                    <div class="me-instruction-title">{% trans "Select the quantities you want to purchase." %}</div>
                    <div class="me-instruction-sub">{% trans "Totals update automatically based on your selections." %}</div>
                </div>
            </div>

            {% if buy_stock_progress.error == "esi_down" %}
            <div class="alert alert-warning d-flex align-items-start gap-2 mb-3" role="status">
                <i class="fas fa-cloud-bolt mt-1" aria-hidden="true"></i>
                <div>
                    <div class="fw-semibold">{% trans "ESI is temporarily unavailable. Using cached stock." %}</div>
                    {% if buy_stock_progress.retry_after_minutes %}
                    <small class="text-muted">
                        {% blocktrans with minutes=buy_stock_progress.retry_after_minutes %}Retry in about {{ minutes }} minute(s).{% endblocktrans %}
                    </small>
                    {% endif %}
                </div>
            </div>
            {% endif %}

            {% if corp_assets_scope_missing %}
            <div class="glass-panel p-4 mb-4">
                <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>
            </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 }}
                    </h5>
                    <form method="post" id="purchaseForm">
                        {% csrf_token %}
                        <input type="hidden" id="hidden_order_reference" name="order_reference" value="">
                        <div class="d-flex align-items-stretch gap-3 mb-3">
                            <div class="d-flex flex-column justify-content-center" role="radiogroup" aria-label="{% trans 'Search mode' %}">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="buySearchMode" id="buySearchModeItem" value="item" checked>
                                    <label class="form-check-label" for="buySearchModeItem">{% trans "Item" %}</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="buySearchMode" id="buySearchModeCategory" value="category">
                                    <label class="form-check-label" for="buySearchModeCategory">{% trans "Category" %}</label>
                                </div>
                            </div>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input
                                    type="text"
                                    id="buySearchInput"
                                    class="form-control"
                                    placeholder="{% trans 'Search by item or category' %}"
                                    aria-label="{% trans 'Search by item or category' %}">
                            </div>
                        </div>
                        <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-group-name="{{ item.group_name|default:'' }}"
                                        data-unit-price="{{ item.sell_price_to_member|floatformat:2 }}"
                                        data-max-qty="{{ item.quantity }}">
                                        <td>
                                            <img
                                                src="{{ item.image_url }}"
                                                alt="{{ item.type_name }}"
                                                class="item-icon">
                                        </td>
                                        <td>
                                            <div class="fw-semibold text-body">{{ item.type_name }}</div>
                                            <div class="small text-body-secondary">{{ item.group_name|default:_('Other') }}</div>
                                        </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 class="qty-cell">
                                                <div class="qty-input-row">
                                                    <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-btns" role="group" aria-label="{% trans 'Quantity shortcuts' %}">
                                                        <button type="button" class="btn btn-secondary btn-sm qty-btn" data-action="zero" title="{% trans 'Zero' %}" aria-label="{% trans 'Zero' %}">
                                                            <i class="fas fa-ban" aria-hidden="true"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-secondary btn-sm qty-btn" data-action="max">{% trans "Max" %}</button>
                                                    </div>
                                                </div>
                                                <div class="qty-error" id="error-{{ item.type_id }}">
                                                    {% trans "Max:" %} {{ item.quantity|intcomma }}
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        <div id="buySearchEmpty" class="alert alert-warning mt-3 d-none mb-0">
                            <i class="fas fa-search me-2"></i>
                            {% trans "No matching items for your search." %}
                        </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>
        </div>
        {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const cleanUrl = new URL(window.location.href);
    if (cleanUrl.searchParams.get('refreshed') === '1') {
        cleanUrl.searchParams.delete('refreshed');
        window.history.replaceState({}, document.title, cleanUrl.toString());
    }

    const qtyInputs = document.querySelectorAll('.qty-input');
    const buySearchInput = document.getElementById('buySearchInput');
    const buySearchModeInputs = document.querySelectorAll('input[name="buySearchMode"]');
    const stockRows = document.querySelectorAll('.stock-row');

    const buySearchPlaceholderByMode = {
        item: '{% trans "Search item" %}',
        category: '{% trans "Search category" %}'
    };

    function updateBuySearchPlaceholder() {
        if (!buySearchInput) {
            return;
        }
        const selectedMode = document.querySelector('input[name="buySearchMode"]:checked')?.value || 'item';
        const placeholder = buySearchPlaceholderByMode[selectedMode] || buySearchPlaceholderByMode.item;
        buySearchInput.placeholder = placeholder;
        buySearchInput.setAttribute('aria-label', placeholder);
    }

    function applyBuyFilter() {
        if (!buySearchInput) {
            return;
        }

        const query = (buySearchInput.value || '').trim().toLowerCase();
        const selectedMode = document.querySelector('input[name="buySearchMode"]:checked')?.value || 'item';
        let visibleCount = 0;

        stockRows.forEach(row => {
            const typeName = (row.dataset.typeName || '').toLowerCase();
            const groupName = (row.dataset.groupName || '').toLowerCase();
            const matches = !query || (selectedMode === 'category' ? groupName.includes(query) : typeName.includes(query));
            row.classList.toggle('d-none', !matches);
            if (matches) {
                visibleCount += 1;
            }
        });

        const emptyState = document.getElementById('buySearchEmpty');
        if (emptyState) {
            emptyState.classList.toggle('d-none', visibleCount > 0);
        }
    }

    if (buySearchInput) {
        buySearchInput.addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
            }
        });
        buySearchInput.addEventListener('input', applyBuyFilter);
        buySearchModeInputs.forEach(input => input.addEventListener('change', () => {
            updateBuySearchPlaceholder();
            applyBuyFilter();
        }));
        updateBuySearchPlaceholder();
        applyBuyFilter();
    }

    document.addEventListener('click', function(event) {
        const button = event.target.closest('.qty-btn');
        if (!button) {
            return;
        }
        const row = button.closest('tr');
        if (!row) {
            return;
        }
        const input = row.querySelector('.qty-input');
        if (!input) {
            return;
        }
        const action = button.dataset.action;
        if (action === 'zero') {
            input.value = 0;
        } else if (action === 'max') {
            input.value = input.dataset.max || 0;
        }
        updateInvoice();
    });

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

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

    function toCents(value) {
        const numeric = Number.parseFloat(value);
        if (!Number.isFinite(numeric)) {
            return 0;
        }
        return Math.round(numeric * 100);
    }

    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 totalCents = 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 unitPriceCents = toCents(row.dataset.unitPrice);
                const subtotalCents = unitPriceCents * effectiveQty;
                const subtotal = subtotalCents / 100;

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

                totalCents += subtotalCents;
                row.classList.add('selected');
            } else {
                row.classList.remove('selected');
            }
        });

        // Match backend `MaterialExchangeBuyOrder.total_price`: ceil to whole ISK.
        const total = Math.ceil(totalCents / 100);

        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 = formatWholeISK(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 %}

    document.querySelectorAll('.js-local-time[data-utc]').forEach(function(node) {
        const utcValue = node.getAttribute('data-utc');
        if (!utcValue) {
            return;
        }
        const date = new Date(utcValue);
        if (Number.isNaN(date.getTime())) {
            return;
        }
        const formatted = new Intl.DateTimeFormat(undefined, {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        }).format(date);
        node.textContent = formatted.replace(/\//g, '-');
    });
});
</script>
{% endblock content %}
