{% extends "layouts/base.html" %}
{% load i18n %}

{% block title %}{% trans "Send to Department" %} - {{ complaint.reference_number }} - PX360{% endblock %}

{% block extra_css %}
<style>
.page-header-gradient {
    background: linear-gradient(135deg, #005696 0%, #0069a8 50%, #007bbd 100%);
    color: white;
    padding: 1.5rem 2rem;
    border-radius: 1rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 10px 15px -3px rgba(0, 86, 150, 0.2);
}

.form-section {
    background: #fff;
    border: 2px solid #e2e8f0;
    border-radius: 1rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
}
.form-section:hover {
    border-color: #005696;
    box-shadow: 0 4px 12px rgba(0, 86, 150, 0.1);
}

.form-label {
    display: block;
    font-size: 0.875rem;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.form-control, .form-select {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 0.75rem;
    font-size: 0.875rem;
    transition: all 0.2s ease;
}
.form-control:focus, .form-select:focus {
    outline: none;
    border-color: #005696;
    box-shadow: 0 0 0 3px rgba(0, 86, 150, 0.1);
}

.hh-btn-primary {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: #005696;
    color: white;
    border-radius: 0.75rem;
    font-weight: 600;
    transition: all 0.2s ease;
    border: none;
    cursor: pointer;
}
.hh-btn-primary:hover {
    background: #007bbd;
}

.hh-btn-secondary {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background: white;
    color: #64748b;
    border: 2px solid #e2e8f0;
    border-radius: 0.75rem;
    font-weight: 600;
    transition: all 0.2s ease;
}
.hh-btn-secondary:hover {
    background: #f1f5f9;
    border-color: #005696;
}
</style>
{% endblock %}

{% block content %}
<!-- Back Button -->
<div class="mb-6">
    <a href="{% url 'complaints:complaint_detail' pk=complaint.pk %}" class="hh-btn hh-btn-secondary">
        <i data-lucide="arrow-left" class="w-4 h-4"></i> {% trans "Back to Complaint" %}
    </a>
</div>

<!-- Header -->
<div class="page-header-gradient">
    <div class="flex items-center gap-2 text-sm text-white/80 mb-2">
        <a href="{% url 'complaints:complaint_list' %}" class="hover:text-white">{% trans "Complaints" %}</a>
        <i data-lucide="chevron-right" class="w-4 h-4"></i>
        <a href="{% url 'complaints:complaint_detail' pk=complaint.pk %}" class="hover:text-white">{{ complaint.reference_number }}</a>
        <i data-lucide="chevron-right" class="w-4 h-4"></i>
        <span class="font-bold">{% trans "Send to Department" %}</span>
    </div>
    <h1 class="text-2xl font-bold">{% trans "Send to Department" %}</h1>
    <p class="text-white/80 mt-1">{{ complaint.title }}</p>
</div>

<form method="post" class="space-y-6">
    {% csrf_token %}
    
    <!-- Department Selection -->
    <section class="form-section">
        <div class="flex items-center justify-between mb-6">
            <h3 class="font-bold text-[#1e293b] text-lg flex items-center gap-2">
                <i data-lucide="building-2" class="w-5 h-5 text-[#005696]"></i>
                {% trans "Select Departments" %}
            </h3>
            <div class="flex gap-2">
                <button type="button" onclick="selectAllDepts()" class="px-3 py-1.5 text-xs font-semibold text-[#005696] border-2 border-[#e2e8f0] rounded-lg hover:border-[#005696] hover:bg-[#f1f5f9] transition">
                    {% trans "Select All" %}
                </button>
                <button type="button" onclick="deselectAll()" class="px-3 py-1.5 text-xs font-semibold text-[#64748b] border-2 border-[#e2e8f0] rounded-lg hover:border-[#005696] hover:bg-[#f1f5f9] transition">
                    {% trans "Deselect All" %}
                </button>
            </div>
        </div>
        
        {% if department_groups %}
        <div class="space-y-4">
            {% for dept_id, dept_info in department_groups.items %}
            <div class="border-2 border-[#e2e8f0] rounded-xl p-4 hover:border-[#005696] transition">
                <div class="flex items-start gap-4">
                    <!-- Department Checkbox -->
                    <div class="pt-1">
                        <input type="checkbox" 
                               name="selected_departments" 
                               value="{{ dept_id }}" 
                               id="dept_{{ dept_id }}"
                               class="dept-checkbox w-5 h-5 text-[#005696] border-2 border-[#e2e8f0] rounded focus:ring-[#005696]"
                               checked>
                    </div>
                    
                    <!-- Department Info -->
                    <div class="flex-1">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 bg-[#005696] rounded-full flex items-center justify-center text-white font-bold text-sm">
                                {{ dept_info.department_name|first }}
                            </div>
                            <div>
                                <h4 class="font-bold text-[#1e293b]">{{ dept_info.department_name }}</h4>
                                <span class="text-xs text-[#64748b]">{% trans "Department" %}</span>
                            </div>
                        </div>
                        
                        <!-- Champion -->
                        <div class="mt-2 pl-4 border-l-2 border-[#005696]/30">
                            <div class="flex items-center gap-2 mb-1">
                                <i data-lucide="crown" class="w-4 h-4 text-amber-500"></i>
                                <span class="text-sm font-semibold text-[#005696]">{% trans "Department Champion:" %}</span>
                                {% if dept_info.champion_name %}
                                <span class="text-sm font-bold text-[#1e293b]">{{ dept_info.champion_name }}</span>
                                {% else %}
                                <span class="text-sm text-amber-600 italic">{% trans "No champion assigned" %}</span>
                                {% endif %}
                            </div>
                            {% if dept_info.champion_name and not dept_info.champion_email %}
                            <div class="mt-1 p-2 bg-red-50 border-2 border-red-200 rounded-lg">
                                <p class="text-xs text-red-600 flex items-center gap-2">
                                    <i data-lucide="alert-triangle" class="w-4 h-4"></i>
                                    {% trans "Champion has no email address. Request cannot be sent." %}
                                </p>
                            </div>
                            {% elif not dept_info.champion_name %}
                            <div class="mt-1 p-2 bg-amber-50 border-2 border-amber-200 rounded-lg">
                                <p class="text-xs text-amber-600 flex items-center gap-2">
                                    <i data-lucide="alert-triangle" class="w-4 h-4"></i>
                                    {% trans "No champion assigned. Please assign a champion before sending." %}
                                </p>
                            </div>
                            {% endif %}
                        </div>
                        
                        <!-- Contact Person Selector -->
                        <div class="mt-3 pl-4 border-l-2 border-[#005696]/20">
                            <label class="block text-sm font-semibold text-[#1e293b] mb-1">{% trans "Send To" %} <span class="text-red-500">*</span></label>
                            <select name="contact_person_{{ dept_id }}" id="contact_person_{{ dept_id }}" class="w-full px-3 py-2 border-2 border-[#e2e8f0] rounded-lg text-sm focus:outline-none focus:border-[#005696]">
                                <option value="">{% trans "Loading contacts..." %}</option>
                            </select>
                        </div>
                        
                        <!-- Department Manager -->
                        {% if dept_info.dept_manager %}
                        <div class="mt-2 pl-4 border-l-2 border-[#005696]/20">
                            <div class="flex items-center gap-2">
                                <i data-lucide="user-check" class="w-4 h-4 text-[#005696]"></i>
                                <span class="text-sm font-semibold text-[#64748b]">{% trans "Department Manager:" %}</span>
                                <span class="text-sm font-bold text-[#1e293b]">{{ dept_info.dept_manager_name }}</span>
                            </div>
                            <p class="text-xs text-[#64748b] mt-1 ml-6">
                                {% trans "Will receive escalation notification" %}
                            </p>
                        </div>
                        {% endif %}
                        
                        <!-- Involved Staff -->
                        <div class="mt-3 pl-4 border-l-2 border-[#e2e8f0]">
                            <p class="text-xs font-semibold text-[#64748b] mb-2">{% trans "Involved Staff:" %}</p>
                            <div class="flex flex-wrap gap-2">
                                {% for s in dept_info.staff_list %}
                                <span class="px-2.5 py-1 bg-[#f1f5f9] rounded-lg text-xs font-bold text-[#1e293b]">
                                    {{ s.staff_name }}
                                    <span class="text-[#64748b] font-normal ml-1">({{ s.role }})</span>
                                </span>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="text-center py-12">
            <i data-lucide="building-2" class="w-16 h-16 mx-auto text-[#e2e8f0] mb-4"></i>
            <p class="text-[#64748b] font-medium">{% trans "No departments involved in this complaint. Add departments first." %}</p>
        </div>
        {% endif %}

        {% if ungrouped_staff %}
        <div class="mt-6 p-4 bg-amber-50 border-2 border-amber-200 rounded-xl">
            <div class="flex items-center gap-2 mb-2">
                <i data-lucide="alert-circle" class="w-5 h-5 text-amber-600"></i>
                <h4 class="font-bold text-amber-800">{% trans "Staff Without Department" %}</h4>
            </div>
            <p class="text-sm text-amber-700 mb-3">{% trans "These staff members are not assigned to any department." %}</p>
            <div class="flex flex-wrap gap-2">
                {% for s in ungrouped_staff %}
                <span class="px-2.5 py-1 bg-white border border-amber-300 rounded-lg text-xs font-bold text-amber-800">
                    {{ s.staff_name }}
                    <span class="text-amber-600 font-normal ml-1">({{ s.role }})</span>
                </span>
                {% endfor %}
            </div>
        </div>
        {% endif %}
    </section>
    
    <!-- Message -->
    <section class="form-section">
        <h3 class="font-bold text-[#1e293b] mb-4 text-lg flex items-center gap-2">
            <i data-lucide="message-square" class="w-5 h-5 text-[#005696]"></i>
            {% trans "Additional Message" %}
        </h3>
        <div>
            <label for="request_message" class="form-label">
                {% trans "Optional message to include in the email" %}
            </label>
            <textarea name="request_message" 
                      id="request_message" 
                      rows="4" 
                      class="form-control resize-none"
                      placeholder="{% trans 'Enter any additional context or instructions for the department champions...' %}"></textarea>
        </div>
    </section>
    
    <!-- Summary -->
    <section class="form-section bg-[#f8fafc]">
        <div class="flex items-center justify-between flex-wrap gap-4">
            <div>
                <h4 class="font-bold text-[#1e293b] mb-1">{% trans "Summary" %}</h4>
                <p class="text-sm text-[#64748b]">
                    <span id="dept-count">0</span> {% trans "department champions will receive explanation links" %}
                </p>
            </div>
            <div class="flex items-center gap-4">
                <a href="{% url 'complaints:complaint_detail' pk=complaint.pk %}" 
                   class="hh-btn hh-btn-secondary">
                    {% trans "Cancel" %}
                </a>
                <button type="submit" 
                        class="hh-btn hh-btn-primary"
                        id="submit-btn"
                        name="action" value="preview">
                    <i data-lucide="eye" class="w-5 h-5"></i>
                    {% trans "Preview Messages" %}
                </button>
            </div>
        </div>
    </section>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    updateCounts();
    lucide.createIcons();
    loadAllDeptContacts();
});

function loadAllDeptContacts() {
    document.querySelectorAll('[id^="contact_person_"]').forEach(function(sel) {
        var deptId = sel.id.replace('contact_person_', '');
        fetch('/organizations/dropdowns/department-contacts/' + deptId + '/')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                sel.innerHTML = '<option value="">{% trans "Select Contact Person" %}</option>';
                data.forEach(function(c) {
                    var opt = document.createElement('option');
                    opt.value = c.staff_id;
                    opt.textContent = c.name + ' (' + c.role_label + ')';
                    sel.appendChild(opt);
                });
            })
            .catch(function() {
                sel.innerHTML = '<option value="">{% trans "Error loading contacts" %}</option>';
            });
    });
}

function selectAllDepts() {
    document.querySelectorAll('.dept-checkbox').forEach(cb => {
        cb.checked = true;
    });
    updateCounts();
}

function deselectAll() {
    document.querySelectorAll('.dept-checkbox').forEach(cb => {
        cb.checked = false;
    });
    updateCounts();
}

function updateCounts() {
    const deptCount = document.querySelectorAll('.dept-checkbox:checked').length;
    document.getElementById('dept-count').textContent = deptCount;
    
    const submitBtn = document.getElementById('submit-btn');
    if (deptCount === 0) {
        submitBtn.disabled = true;
        submitBtn.classList.add('opacity-50', 'cursor-not-allowed');
    } else {
        submitBtn.disabled = false;
        submitBtn.classList.remove('opacity-50', 'cursor-not-allowed');
    }
}

document.querySelectorAll('.dept-checkbox').forEach(cb => {
    cb.addEventListener('change', updateCounts);
});
</script>
{% endblock %}
