{% extends 'core/base.html' %}
{% load currency_filters %}
{% load static %}

{% block title %}{{ product.name }} - SwiftPOS{% endblock %}

{% block topbar_title %}
Product Detail
{% endblock %}

{% block content %}
<div class="container-fluid px-0">

    <!-- Toast Messages -->
    <div class="swiftpos-toast-container">
        {% if messages %}
            {% for message in messages %}
                <div class="swiftpos-toast swiftpos-toast-{{ message.tags }}">
                    <div class="toast-icon">
                        {% if message.tags == 'success' %}
                            <i class="fas fa-check-circle"></i>
                        {% elif message.tags == 'error' or message.tags == 'danger' %}
                            <i class="fas fa-exclamation-circle"></i>
                        {% elif message.tags == 'warning' %}
                            <i class="fas fa-exclamation-triangle"></i>
                        {% else %}
                            <i class="fas fa-info-circle"></i>
                        {% endif %}
                    </div>
                    <div class="toast-text">
                        {{ message }}
                    </div>
                </div>
            {% endfor %}
        {% endif %}
    </div>

    <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
        <div>
            <h5 class="mb-0">Product: {{ product.name }}</h5>
            <div class="text-muted small">
                SKU: {{ product.sku }}{% if product.barcode %} · Barcode: {{ product.barcode }}{% endif %}
            </div>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <a href="{% url 'inventory:product_list' %}"
               class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2">
                <i class="fas fa-list"></i> Products
            </a>
            <a href="{% url 'inventory:reduce_stock' product.id %}"
               class="btn btn-outline-danger btn-sm d-flex align-items-center gap-2">
                <i class="fas fa-minus-circle"></i> Reduce stock
            </a>
            <a href="{% url 'inventory:restock_product' product.id %}"
               class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2">
                <i class="fas fa-plus-circle"></i> Restock
            </a>
            {% if request.company.plan.feature_product_variants %}
            <a href="{% url 'inventory:product_variants' product.id %}"
               class="btn btn-outline-info btn-sm d-flex align-items-center gap-2">
                <i class="fas fa-swatchbook"></i> Variants
            </a>
            {% endif %}
            <a href="{% url 'inventory:edit_product' product.id %}"
               class="btn btn-primary btn-sm d-flex align-items-center gap-2">
                <i class="fas fa-pen"></i> Edit
            </a>
        </div>
    </div>

    <div class="row g-3">
        <!-- Left: image + key info -->
        <div class="col-lg-4">
            <div class="card mb-3">
                <div class="card-body">
                    {% if product.image %}
                        <div class="ratio ratio-4x3 mb-2">
                            <img src="{{ product.image.url }}"
                                 alt="{{ product.name }}"
                                 class="img-fluid rounded"
                                 style="object-fit: cover;">
                        </div>
                    {% else %}
                        <div class="d-flex align-items-center justify-content-center mb-2 rounded"
                             style="background: var(--sp-surface-muted); height: 220px;">
                            <i class="fas fa-box-open fa-3x text-muted"></i>
                        </div>
                    {% endif %}
                    <div class="small text-muted">
                        Image preview (optional). You can update it from "Edit" above.
                    </div>
                </div>
            </div>

            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-box"></i> Stock
                        {% if has_variants %}
                        <span class="badge bg-primary-subtle text-primary border-0 ms-1" style="font-size:.7rem;">Variant-managed</span>
                        {% endif %}
                    </h6>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small text-muted">Current stock</span>
                        {% if has_variants %}
                        <span class="h5 mb-0">{{ variant_stock_total }}</span>
                        {% else %}
                        <span class="h5 mb-0">{{ product.stock_quantity }}</span>
                        {% endif %}
                    </div>
                    {% if has_variants %}
                    <div class="alert alert-info py-1 px-2 small mb-2">
                        <i class="fas fa-info-circle me-1"></i>
                        Stock is managed per variant. Total above = sum of all variant stocks.
                    </div>
                    {% endif %}
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small text-muted">Minimum stock</span>
                        <span class="small">{{ product.minimum_stock }}</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small text-muted">Status</span>
                        <span>
                            {% if has_variants %}
                                {% if variant_stock_total > product.minimum_stock %}
                                <span class="badge bg-success-subtle text-success border border-success-subtle">In Stock</span>
                                {% elif variant_stock_total > 0 %}
                                <span class="badge bg-warning text-dark">Low Stock</span>
                                {% else %}
                                <span class="badge bg-danger text-light">Out of Stock</span>
                                {% endif %}
                            {% elif product.stock_status == 'in_stock' %}
                                <span class="badge bg-success-subtle text-success border border-success-subtle">
                                    {{ product.get_stock_status_display }}
                                </span>
                            {% elif product.stock_status == 'low_stock' %}
                                <span class="badge bg-warning text-dark">
                                    {{ product.get_stock_status_display }}
                                </span>
                            {% else %}
                                <span class="badge bg-danger text-light">
                                    {{ product.get_stock_status_display }}
                                </span>
                            {% endif %}
                        </span>
                    </div>
                </div>
            </div>

            <!-- Branch Allocations Card -->
            <div class="card mb-3 shadow-sm border-0">
                <div class="card-header bg-white">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-boxes"></i> Store Allocations
                        {% if has_variants %}
                        <span class="badge bg-primary-subtle text-primary border-0 ms-1" style="font-size:.7rem;">By variant stock</span>
                        {% endif %}
                    </h6>
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="small text-muted ps-3">Branch</th>
                                <th class="small text-muted text-end pe-3">Quantity</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% if has_variants %}
                                {# Show per-branch variant stock totals #}
                                {% if variant_branch_stocks %}
                                    {% for vbs in variant_branch_stocks %}
                                    <tr>
                                        <td class="ps-3 small fw-semibold">{{ vbs.branch.name }}</td>
                                        <td class="text-end pe-3 small">
                                            <span class="badge {% if vbs.quantity > 0 %}bg-success-subtle text-success{% else %}bg-secondary-subtle text-secondary{% endif %} border-0 px-2 py-1">
                                                {{ vbs.quantity }}
                                            </span>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                {% else %}
                                    <tr>
                                        <td colspan="2" class="text-center text-muted small py-2">
                                            <i class="fas fa-info-circle me-1"></i>
                                            No branch-level variant stock yet. Use
                                            <a href="{% url 'inventory:product_variants' product.id %}">Manage Variants</a>
                                            → Restock to add branch stock.
                                        </td>
                                    </tr>
                                {% endif %}
                                {# Also show combined total from variant global stocks #}
                                <tr class="table-light">
                                    <td class="ps-3 small text-muted">Global (all variants)</td>
                                    <td class="text-end pe-3 small">
                                        <span class="badge bg-primary-subtle text-primary border-0 px-2 py-1">
                                            {{ variant_stock_total }}
                                        </span>
                                    </td>
                                </tr>
                            {% elif branch_stocks %}
                                {% for bs in branch_stocks %}
                                    <tr>
                                        <td class="ps-3 small fw-semibold">{{ bs.branch.name|default:"Main Branch" }}</td>
                                        <td class="text-end pe-3 small">
                                            <span class="badge {% if bs.quantity > 0 %}bg-success-subtle text-success{% else %}bg-danger-subtle text-danger{% endif %} border-0 px-2 py-1">
                                                {{ bs.quantity }}
                                            </span>
                                        </td>
                                    </tr>
                                {% endfor %}
                            {% else %}
                                <tr>
                                    <td colspan="2" class="text-center text-muted small py-3">
                                        No branch allocations set yet.
                                    </td>
                                </tr>
                            {% endif %}
                        </tbody>
                    </table>
                </div>
            </div>
            <!-- End Branch Allocations Card -->

        </div>

        <!-- Right: pricing, meta, description -->
        <div class="col-lg-8">
            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-circle-info"></i> Product Information
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-2">
                        <div class="col-md-4">
                            <div class="small text-muted mb-1">Selling price</div>
                            <div class="price">{% money product.price %}</div>
                        </div>
                        <div class="col-md-4">
                            <div class="small text-muted mb-1">Cost price</div>
                            <div class="h6 mb-0">{% money product.cost_price %}</div>
                        </div>
                        <div class="col-md-4">
                            <div class="small text-muted mb-1">Category</div>
                            <div>
                                {{ product.category.name|default:"Uncategorized" }}
                            </div>
                        </div>
                    </div>

                    <hr>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="small text-muted mb-1">Supplier</div>
                            <div>{{ product.supplier|default:"Not specified" }}</div>
                        </div>
                        <div class="col-md-6">
                            <div class="small text-muted mb-1">Created</div>
                            <div>
                                {{ product.created_at|date:"Y-m-d" }}
                                <span class="text-muted small">
                                    {{ product.created_at|time:"H:i" }}
                                </span>
                            </div>
                        </div>
                    </div>

                    {% if product.description %}
                        <hr>
                        <div class="small text-muted mb-1">Description</div>
                        <p class="mb-0">
                            {{ product.description }}
                        </p>
                    {% endif %}
                </div>
            </div>

            <!-- Variants Summary Card -->
            {% if request.company.plan.feature_product_variants %}
            <div class="card mb-3 shadow-sm border-0" id="product_variants_section">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h6 class="card-title mb-0 d-flex align-items-center gap-2">
                        <i class="fas fa-layer-group"></i> Product Variants
                    </h6>
                    <a href="{% url 'inventory:product_variants' product.id %}" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-cog"></i> Manage Variants
                    </a>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="small text-muted ps-3 py-2">Attributes</th>
                                    <th class="small text-muted py-2">SKU</th>
                                    <th class="small text-muted py-2">Price</th>
                                    <th class="small text-muted py-2">Stock</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for variant in product.variants.all %}
                                <tr>
                                    <td class="ps-3 fw-bold small py-2">
                                        <div class="d-flex flex-wrap gap-1">
                                        {% for attr in variant.attributes.all %}
                                            <span class="badge bg-light text-dark border">{{ attr.attribute_name|title }}: {{ attr.attribute_value }}</span>
                                        {% empty %}
                                            <span class="text-muted">Standard</span>
                                        {% endfor %}
                                        </div>
                                    </td>
                                    <td class="small text-muted">{{ variant.sku }}</td>
                                    <td class="small text-success fw-bold">{% money variant.price %}</td>
                                    <td class="small">
                                        {# Show branch stock total for this variant if available #}
                                        {% with stock=variant.stock_quantity %}
                                        {% if stock <= 0 %}
                                            <span class="badge bg-danger-subtle text-danger border-0">Out</span>
                                        {% else %}
                                            <span class="badge bg-success-subtle text-success border-0">{{ stock }}</span>
                                        {% endif %}
                                        {% endwith %}
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="4" class="text-center text-muted small py-4">
                                        <i class="fas fa-swatchbook fa-2x opacity-25 d-block mb-2"></i>
                                        No variants configured for this product.<br>
                                        <a href="{% url 'inventory:product_variants' product.id %}" class="btn btn-sm btn-primary mt-2">Add First Variant</a>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>

                    </div>
                </div>
            </div>
            {% endif %}
            <!-- End Variants Summary Card -->

            {# --- Product Barcode card --- #}
<div class="card shadow-sm mt-3">
    <div class="card-header border-0 d-flex justify-content-between align-items-center">
        <h6 class="mb-0">Product Barcode</h6>
        {% if product.barcode %}
            <span class="badge bg-success-subtle text-success small">
                {{ product.barcode }}
            </span>
        {% else %}
            <span class="badge bg-danger-subtle text-danger small">
                No barcode set
            </span>
        {% endif %}
    </div>

    <div class="card-body text-center">
        {% if product.barcode %}
            <canvas id="productBarcodeCanvas"
                    style="max-width: 260px; width: 100%; height: auto;"></canvas>

            <div class="d-flex justify-content-center gap-2 mt-3">
                <button type="button"
                        class="btn btn-outline-primary btn-sm"
                        id="downloadBarcodeBtn">
                    <i class="fas fa-download"></i> Save Image
                </button>
                <a href="{% url 'inventory:print_product_barcode' product.id %}" target="_blank"
                   class="btn btn-primary btn-sm fw-medium shadow-sm">
                    <i class="fas fa-print"></i> Print Label
                </a>
            </div>

            <p class="text-muted small mt-2 mb-0">
                The image includes the barcode and product name for easy recognition.
            </p>
        {% else %}
            <p class="text-muted small mb-0">
                This product does not have a barcode yet. Set a barcode on the edit page to generate an image.
            </p>
        {% endif %}
    </div>
</div>

            <!-- Quick links -->
            <div class="card">
                <div class="card-body d-flex flex-wrap gap-2">
                    <a href="{% url 'inventory:restock_product' product.id %}"
                       class="btn btn-outline-secondary btn-sm d-flex align-items-center gap-2">
                        <i class="fas fa-plus-circle"></i> Restock this product
                    </a>
                    <a href="{% url 'inventory:reduce_stock' product.id %}"
                       class="btn btn-outline-danger btn-sm d-flex align-items-center gap-2">
                        <i class="fas fa-minus-circle"></i> Reduce stock
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
{% block extra_js %}
    {{ block.super|default:"" }}

    <!-- JsBarcode CDN -->
    <script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>

    <script>
    document.addEventListener("DOMContentLoaded", function () {
        const barcodeValue = "{{ product.barcode|default_if_none:''|escapejs }}";
        const productName = "{{ product.name|escapejs }}";

        const canvas = document.getElementById("productBarcodeCanvas");
        const downloadBtn = document.getElementById("downloadBarcodeBtn");

        if (!canvas || !barcodeValue) {
            return; // nothing to render
        }

        // Generate barcode into the canvas
        try {
            JsBarcode(canvas, barcodeValue, {
                format: "CODE128",          // works well for generic numeric/text barcodes
                displayValue: true,         // show text under barcode
                text: productName,          // use product name as label under barcode
                font: "Poppins, Arial, sans-serif",
                fontSize: 14,
                textMargin: 4,
                margin: 10,
                lineColor: "#111827",
                width: 2,                   // bar thickness
                height: 60                  // bar height
            });
        } catch (e) {
            console.error("Barcode render error:", e);
        }

        if (downloadBtn) {
            downloadBtn.addEventListener("click", function () {
                try {
                    // Create a download link from the canvas
                    const dataUrl = canvas.toDataURL("image/png");

                    const safeName = (productName || "product")
                        .toLowerCase()
                        .replace(/[^a-z0-9]+/g, "_")
                        .replace(/^_+|_+$/g, "");

                    const link = document.createElement("a");
                    link.href = dataUrl;
                    link.download = safeName + "_barcode.png";
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                } catch (e) {
                    console.error("Download failed:", e);
                    alert("Unable to save barcode image in this browser.");
                }
            });
        }
    });
    </script>
{% endblock %}

{% endblock %}