{% extends 'core/base.html' %}
{% 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>
            <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
                    </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>
                        <span class="h5 mb-0">{{ product.stock_quantity }}</span>
                    </div>
                    <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 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>
        </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">{{ currency_symbol }}{{ product.price }}</div>
                        </div>
                        <div class="col-md-4">
                            <div class="small text-muted mb-1">Cost price</div>
                            <div class="h6 mb-0">{{ currency_symbol }}{{ 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>

            {# --- 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>

            <button type="button"
                    class="btn btn-outline-primary btn-sm mt-2"
                    id="downloadBarcodeBtn">
                Save barcode image
            </button>

            <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 %}