{% extends "base.html" %}
{% load static %}
{% block title %}Booking Tags - {{ booking.booking_id }}{% endblock %}

{% block content %}
<div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
    <div class="breadcrumb-title pe-3">Tags for {{ booking.booking_id }}</div>
    <div class="ps-3">
        <span class="badge bg-primary">{{ booking.total_quantity }} Items</span>
    </div>
    <div class="ms-auto">
        <a href="{% url 'booking-tag-print' booking.id %}" target="_blank" class="btn btn-info text-white me-2">
            <i class="bi bi-printer"></i> Print All Tags
        </a>
        <a href="{% url 'tag-management' %}" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> Back to List
        </a>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <!-- Booking Details Card -->
        <div class="card mb-3">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="text-muted small">Customer Name</label>
                        <div class="fw-bold">{{ booking.user.first_name }} {{ booking.user.last_name }}</div>
                    </div>
                    <div class="col-md-3">
                        <label class="text-muted small">Order ID</label>
                        <div class="fw-bold">{{ booking.booking_id }}</div>
                    </div>
                    <div class="col-md-3">
                        <label class="text-muted small">Order Date</label>
                        <div class="fw-bold">{{ booking.created_at|date:"d M Y" }}</div>
                    </div>
                    <div class="col-md-3">
                        <label class="text-muted small">Delivery Date (Est.)</label>
                        <div class="fw-bold">{{ delivery_date|date:"d M Y" }}</div>
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-12">
                        <label class="text-muted small mb-2">Order Summary (Standard)</label>
                        {% if order_details %}
                        <div class="table-responsive mb-3">
                            <table class="table table-sm table-bordered mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Service Type</th>
                                        <th>Category</th>
                                        <th>Item</th>
                                        <th>Quantity</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for service, categories in order_details.items %}
                                        {% for category, items in categories.items %}
                                            {% for item in items %}
                                            <tr>
                                                {% if forloop.first %}
                                                <td rowspan="{{ items|length }}" class="align-middle">{{ service|capfirst }}</td>
                                                <td rowspan="{{ items|length }}" class="align-middle">{{ category|capfirst }}</td>
                                                {% endif %}
                                                <td>{{ item.item_name }}</td>
                                                <td>{{ item.item_quantity }}</td>
                                            </tr>
                                            {% endfor %}
                                        {% endfor %}
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% else %}
                        <div class="text-muted mb-3">No standard items.</div>
                        {% endif %}

                        <label class="text-muted small mb-2">Premium Summary</label>
                        {% if premium_details %}
                        <div class="table-responsive mb-3">
                            <table class="table table-sm table-bordered mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Service Type</th>
                                        <th>Category</th>
                                        <th>Item</th>
                                        <th>Quantity</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for service, categories in premium_details.items %}
                                        {% for category, items in categories.items %}
                                            {% for item in items %}
                                            <tr>
                                                {% if forloop.first %}
                                                <td rowspan="{{ items|length }}" class="align-middle">{{ service|capfirst }}</td>
                                                <td rowspan="{{ items|length }}" class="align-middle">{{ category|capfirst }}</td>
                                                {% endif %}
                                                <td>{{ item.item_name }}</td>
                                                <td>{{ item.item_quantity }}</td>
                                            </tr>
                                            {% endfor %}
                                        {% endfor %}
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% else %}
                        <div class="text-muted mb-3">No premium items.</div>
                        {% endif %}

                        <label class="text-muted small mb-2">Luxury Summary</label>
                        {% if luxury_details %}
                        <div class="table-responsive mb-3">
                            <table class="table table-sm table-bordered mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Service Type</th>
                                        <th>Category</th>
                                        <th>Item</th>
                                        <th>Quantity</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for service, categories in luxury_details.items %}
                                        {% for category, items in categories.items %}
                                            {% for item in items %}
                                            <tr>
                                                {% if forloop.first %}
                                                <td rowspan="{{ items|length }}" class="align-middle">{{ service|capfirst }}</td>
                                                <td rowspan="{{ items|length }}" class="align-middle">{{ category|capfirst }}</td>
                                                {% endif %}
                                                <td>{{ item.item_name }}</td>
                                                <td>{{ item.item_quantity }}</td>
                                            </tr>
                                            {% endfor %}
                                        {% endfor %}
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% else %}
                        <div class="text-muted mb-3">No luxury items.</div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- Tags List Card -->
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="card-title mb-0">Item Tags</h5>
                    <form method="get" class="d-flex gap-2">
                        <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
                            <option value="">All Status</option>
                            <option value="ok" {% if status_filter == 'ok' %}selected{% endif %}>OK (Not Damaged)</option>
                            <option value="damaged" {% if status_filter == 'damaged' %}selected{% endif %}>Damaged</option>
                        </select>
                    </form>
                </div>

                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover align-middle">
                        <thead>
                            <tr>
                                <th>Tag ID</th>
                                <th>Item</th>
                                <th>Color</th>
                                <th>Status</th>
                                <th>Description</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for tag in tags %}
                            <tr>
                                <td><span class="badge bg-dark">{{ tag.tag }}</span></td>
                                <td>
                                    {{ tag.garment.name }} <br>
                                    <small class="text-muted">{{ tag.service.service_name }} / {{ tag.category.name }}</small>
                                </td>
                                <td>{{ tag.color|default:"-" }}</td>
                                <td>
                                    {% if tag.is_damaged %}
                                        <span class="badge bg-danger">Damaged</span>
                                    {% else %}
                                        <span class="badge bg-success">OK</span>
                                    {% endif %}
                                </td>
                                <td>{{ tag.damage_description|default:"-" }}</td>
                                <td>
                                    <div class="d-flex gap-2">
                                        <button class="btn btn-sm btn-warning edit-tag-btn" 
                                            data-id="{{ tag.id }}" 
                                            data-tag="{{ tag.tag }}"
                                            data-color="{{ tag.color }}"
                                            data-damaged="{{ tag.is_damaged|yesno:'true,false' }}"
                                            data-desc="{{ tag.damage_description }}">
                                            <i class="bi bi-pencil"></i> Edit
                                        </button>
                                        <button class="btn btn-sm btn-danger delete-tag-btn" data-id="{{ tag.id }}" data-tag="{{ tag.tag }}">
                                            <i class="bi bi-trash"></i> Delete
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="6" class="text-center">No tags found for this booking.</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Tag Modal -->
<div class="modal fade" id="editTagModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Tag: <span id="modalTagLabel"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="editTagId">
                <div class="mb-3">
                    <label class="form-label">Color</label>
                    <input type="text" class="form-control" id="editTagColor">
                </div>
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="editTagDamaged">
                        <label class="form-check-label">Is Damaged?</label>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Damage Description</label>
                    <textarea class="form-control" id="editTagDesc" rows="3"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveTagBtn">Save Changes</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        const $modal = new bootstrap.Modal(document.getElementById('editTagModal'));
        
        $('.edit-tag-btn').on('click', function() {
            const btn = $(this);
            $('#editTagId').val(btn.data('id'));
            $('#modalTagLabel').text(btn.data('tag'));
            $('#editTagColor').val(btn.data('color'));
            $('#editTagDamaged').prop('checked', btn.data('damaged') === true);
            $('#editTagDesc').val(btn.data('desc'));
            $modal.show();
        });

        $('#saveTagBtn').on('click', function() {
            const id = $('#editTagId').val();
            const color = $('#editTagColor').val();
            const isDamaged = $('#editTagDamaged').is(':checked');
            const desc = $('#editTagDesc').val();

            // Use the existing update endpoint
            const urlTemplate = "{% url 'booking-item-update' 0 %}";
            const url = urlTemplate.replace('0', id);

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({
                    color: color,
                    is_damaged: isDamaged,
                    damage_description: desc
                })
            }).then(response => {
                if (response.ok) {
                    // alert("Tag updated successfully!");
                    location.reload();
                } else {
                    alert("Error updating tag.");
                }
            });
        });

        // Delete Tag Handler
        $('.delete-tag-btn').on('click', function() {
            const btn = $(this);
            const id = btn.data('id');
            const tag = btn.data('tag');

            if (confirm(`Are you sure you want to delete tag ${tag}?`)) {
                const urlTemplate = "{% url 'booking-item-delete' 0 %}";
                const url = urlTemplate.replace('0', id);

                fetch(url, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}'
                    }
                }).then(response => {
                    if (response.ok) {
                        location.reload();
                    } else {
                        alert("Error deleting tag.");
                    }
                });
            }
        });
    });
</script>
{% endblock %}