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

{% block page_title %}{% trans "Sell Order Details" %} - {{ order.order_reference }}{% 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/material_exchange_order_details.css' %}">
{% endblock extra_css %}

{% block content %}
<main class="bg-body p-4 sell-order-detail">
    <div class="container-fluid my-0 bg-body">
        <!-- Header -->
        <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-file-invoice-dollar me-2"></i>
                        {% trans "Sell Order Details" %}
                    </h2>
                    <p class="description">{% trans "Order" %} #{{ order.id }}</p>
                </div>
                {% url 'indy_hub:my_orders' as my_orders_url %}
                {% with back_url=request.GET.next|default:my_orders_url %}
                <div class="d-flex gap-2">
                    <a href="{{ back_url }}" class="btn btn-outline-light">
                        <i class="fas fa-arrow-left me-1"></i>{% trans "My Orders" %}
                    </a>
                </div>
                {% endwith %}
            </div>
            <i class="fas fa-file-invoice-dollar header-bg"></i>
        </div>

        <!-- Order Reference Display -->
        <div class="order-reference-display order-summary">
            <div class="order-summary-grid">
                <div class="order-summary-icon" aria-hidden="true">
                    <i class="fas fa-qrcode"></i>
                </div>

                <div class="order-summary-main">
                    <div class="order-summary-label">{% trans "Order Reference" %}</div>
                    <div class="order-summary-ref-row">
                        <div id="orderReference" class="order-summary-ref">{{ order.order_reference }}</div>
                        <button type="button" class="btn btn-warning btn-sm copy-button" onclick="copyOrderReference(this)" title="{% trans "Copy" %}">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>

                    <div class="order-summary-meta">
                        <span class="order-summary-chip">
                            <i class="fas fa-building me-1" aria-hidden="true"></i>
                            <span class="order-summary-chip-label">{% trans "Corporation" %}:</span>
                            <span id="corporationName" class="order-summary-chip-value">{{ corporation_name }}</span>
                            <button type="button" class="btn btn-link p-0 ms-2 order-summary-chip-copy" onclick="copyCorporationName(this)" title="{% trans "Copy" %}">
                                <i class="fas fa-copy" aria-hidden="true"></i>
                            </button>
                        </span>

                        <span class="order-summary-sep" aria-hidden="true">•</span>

                        <span class="order-summary-chip">
                            <i class="fas fa-coins me-1" aria-hidden="true"></i>
                            <span class="order-summary-chip-label">{% trans "Total" %}:</span>
                            <span class="order-summary-chip-value text-warning fw-bold">
                                <span id="orderTotalFormatted" data-raw="{{ order.total_price|floatformat:0 }}"></span> ISK
                            </span>
                            <button type="button" class="btn btn-link p-0 ms-2 order-summary-chip-copy" onclick="copyOrderTotal(this)" title="{% trans "Copy" %}">
                                <i class="fas fa-copy" aria-hidden="true"></i>
                            </button>
                        </span>
                    </div>
                </div>

                <div class="order-summary-actions">
                    {% if order.status != 'completed' and order.status != 'rejected' and order.status != 'cancelled' %}
                        <a href="{% url 'indy_hub:sell_order_delete' order.id %}" class="btn btn-outline-danger btn-sm">
                            <i class="fas fa-trash me-1"></i>{% trans "Delete" %}
                        </a>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Left Column: Order Info -->
            <div class="col-lg-8">
                <!-- Status Card -->
                <div class="card mb-4">
                    <div class="card-header bg-success bg-opacity-10">
                        <h5 class="mb-0">
                            <i class="fas fa-info-circle me-2"></i>{% trans "Order Status" %}
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3>
                                    <span class="order-status-badge status-{{ order.status }}">
                                        <i class="fas {{ timeline.0.icon }} status-icon"></i>
                                        {{ order.get_status_display }}
                                    </span>
                                </h3>
                            </div>
                            <div class="text-end">
                                <small class="text-muted">
                                    {% trans "Created:" %} {{ order.created_at|date:"Y-m-d H:i" }}
                                </small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- How This Works / Contract Instructions (visible until validated) -->
                {% if order.status == 'draft' or order.status == 'awaiting_validation' or order.status == 'validated' %}
                    <div class="card mb-4">
                        <div class="card-header bg-info bg-opacity-10">
                            <h5 class="mb-0">
                                <i class="fas fa-info-circle me-2"></i>{% trans "How This Works" %}
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="contract-instructions">
                                <p class="mb-3">
                                    <i class="fas fa-handshake me-2 text-info"></i>
                                    {% trans "You create an Item Exchange contract to the corporation with the details below. The system auto-validates the contract once it matches." %}
                                </p>
                                <ol class="mb-3">
                                    <li>
                                        <strong>{% trans "Type:" %}</strong> {% trans "Item Exchange" %}
                                    </li>
                                    <li>
                                        <strong>{% trans "Assign to:" %}</strong>
                                        {{ corporation_name }}
                                    </li>
                                    <li>
                                        <strong>{% trans "Location:" %}</strong>
                                        {{ config.structure_name }}
                                    </li>
                                    <li>
                                        <strong>{% trans "Price:" %}</strong>
                                        <span class="text-warning fw-bold">{{ order.total_price|floatformat:0|intcomma }} ISK</span>
                                    </li>
                                    <li>
                                        <strong class="text-danger">{% trans "Title/Description:" %}</strong>
                                        <span class="text-warning fw-bold">{{ order.order_reference }}</span>
                                        <span class="text-danger">({% trans "REQUIRED!" %})</span>
                                    </li>
                                    <li>
                                        <strong>{% trans "Duration:" %}</strong> {% trans "4 weeks" %}
                                    </li>
                                </ol>
                                <div class="alert alert-warning mt-3 mb-0">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    <strong>{% trans "Important:" %}</strong>
                                    {% trans "Include the exact order reference in the contract title. Once the contract matches these details, validation happens automatically within a few minutes." %}
                                </div>
                            </div>
                        </div>
                    </div>
                {% endif %}

                <!-- Items List -->
                <div class="card mb-4">
                    <div class="card-header bg-success bg-opacity-10">
                        <h5 class="mb-0">
                            <i class="fas fa-boxes me-2"></i>{% trans "Items" %} ({{ items.count }})
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead>
                                    <tr>
                                        <th>{% trans "Item" %}</th>
                                        <th class="text-end">{% trans "Quantity" %}</th>
                                        <th class="text-end">{% trans "Unit Price" %}</th>
                                        <th class="text-end">{% trans "Total" %}</th>
                                        {% if order.status != 'draft' and order.status != 'awaiting_validation' %}
                                            <th class="text-center">{% trans "Validated" %}</th>
                                        {% endif %}
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for item in items %}
                                        <tr>
                                            <td>
                                                <strong>{{ item.type_name }}</strong>
                                            </td>
                                            <td class="text-end">{{ item.quantity|intcomma }}</td>
                                            <td class="text-end">{{ item.unit_price|floatformat:2|intcomma }} ISK</td>
                                            <td class="text-end fw-bold text-warning">
                                                {{ item.total_price|floatformat:2|intcomma }} ISK
                                            </td>
                                            {% if order.status != 'draft' and order.status != 'awaiting_validation' %}
                                                <td class="text-center">
                                                    {% if item.esi_contract_validated %}
                                                        <i class="fas fa-check-circle text-success"></i>
                                                    {% else %}
                                                        <i class="fas fa-hourglass-half text-warning"></i>
                                                    {% endif %}
                                                </td>
                                            {% endif %}
                                        </tr>
                                    {% endfor %}
                                </tbody>
                                <tfoot>
                                    <tr class="table-active fw-bold">
                                        <td colspan="3" class="text-end">{% trans "TOTAL PAYOUT:" %}</td>
                                        <td class="text-end text-success fs-5">
                                            {{ order.total_price|floatformat:0|intcomma }} ISK
                                        </td>
                                        {% if order.status != 'draft' %}
                                            <td></td>
                                        {% endif %}
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Right Column: Timeline -->
            <div class="col-lg-4">
                <div class="card mb-4">
                    <div class="card-header bg-primary bg-opacity-10">
                        <h5 class="mb-0">
                            <i class="fas fa-history me-2"></i>{% trans "Timeline" %}
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="timeline">
                            {% for step in timeline %}
                                <div class="timeline-item">
                                    <div class="timeline-icon {% if step.completed %}completed{% else %}pending{% endif %}">
                                        <i class="{{ step.icon }}"></i>
                                    </div>
                                    <div>
                                        <h6 class="mb-1">{{ step.status }}</h6>
                                        {% if step.timestamp %}
                                            <small class="text-muted">
                                                <i class="far fa-clock me-1"></i>
                                                {{ step.timestamp|date:"Y-m-d H:i" }}
                                            </small>
                                        {% endif %}
                                        {% if step.user %}
                                            <div>
                                                <small class="text-muted">
                                                    <i class="far fa-user me-1"></i>
                                                    {{ step.user }}
                                                </small>
                                            </div>
                                        {% endif %}
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- Notes (if any) -->
                {% if order.notes %}
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-sticky-note me-2"></i>{% trans "Notes" %}
                            </h5>
                        </div>
                        <div class="card-body">
                            <p class="mb-0">{{ order.notes }}</p>
                        </div>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
</main>

<script>
function flashCopied(btn) {
    const originalHTML = btn.innerHTML;
    const originalClass = btn.className;

    btn.innerHTML = '<i class="fas fa-check" aria-hidden="true"></i>';
    btn.className = `${originalClass} text-success`;

    setTimeout(() => {
        btn.innerHTML = originalHTML;
        btn.className = originalClass;
    }, 1200);
}

function formatOrderTotalForEve(rawValue) {
    if (!rawValue) {
        return '';
    }

    const normalized = String(rawValue).trim().replace(/\s+/g, '').replace(',', '.');
    const value = Number(normalized);
    if (!Number.isFinite(value)) {
        return '';
    }
    return String(Math.ceil(value));
}

function formatOrderTotal(rawValue) {
    if (!rawValue) {
        return '';
    }

    const normalized = String(rawValue).replace(',', '.');
    const numeric = Number(normalized);
    if (!Number.isFinite(numeric)) {
        return String(rawValue);
    }

    return new Intl.NumberFormat('fr-FR', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
    }).format(Math.ceil(numeric));
}

document.addEventListener('DOMContentLoaded', () => {
    const totalEl = document.getElementById('orderTotalFormatted');
    if (totalEl) {
        totalEl.textContent = formatOrderTotal(totalEl.dataset.raw);
    }
});

function copyOrderReference(btn) {
    const reference = document.getElementById('orderReference').textContent;
    navigator.clipboard.writeText(reference).then(() => {
        const originalHTML = btn.innerHTML;
        const originalClass = btn.className;
        btn.innerHTML = '<i class="fas fa-check me-2" aria-hidden="true"></i>{% trans "Copied!" %}';
        btn.className = originalClass.replace('btn-warning', 'btn-success');

        setTimeout(() => {
            btn.innerHTML = originalHTML;
            btn.className = originalClass;
        }, 1600);
    }).catch(err => {
        console.error('Failed to copy:', err);
        alert('Failed to copy to clipboard');
    });
}

function copyCorporationName(btn) {
    const name = document.getElementById('corporationName').textContent;
    navigator.clipboard.writeText(name).then(() => {
        flashCopied(btn);
    }).catch(err => {
        console.error('Failed to copy:', err);
        alert('Failed to copy to clipboard');
    });
}

function copyOrderTotal(btn) {
    const totalEl = document.getElementById('orderTotalFormatted');
    const totalRaw = totalEl ? totalEl.dataset.raw : '';
    const totalForEve = formatOrderTotalForEve(totalRaw);
    navigator.clipboard.writeText(totalForEve).then(() => {
        flashCopied(btn);
    }).catch(err => {
        console.error('Failed to copy:', err);
        alert('Failed to copy to clipboard');
    });
}
</script>
{% endblock content %}
