{% extends "base.html" %}
{% load static %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'admin/css/vendor/select2/select2.min.css' %}">
<style>
    /* Select2 Bootstrap 5 compatibility or similar overrides */
    .select2-container--default .select2-selection--multiple {
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        min-height: 45px;
        padding: 4px 8px;
    }
    .select2-container--default.select2-container--focus .select2-selection--multiple {
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: #0d6efd;
        border: none;
        color: white;
        border-radius: 4px;
        padding: 2px 8px;
        margin-top: 4px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        color: white;
        margin-right: 5px;
        border: none;
        background: transparent;
        cursor: pointer;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
        color: #f8f9fa;
        background: transparent;
    }
    .select2-container {
        width: 100% !important;
    }
    .select2-search__field {
        margin-top: 4px !important;
        width: 100% !important;
    }
</style>
{% endblock %}

{% block content %}
<div class="container py-5">
    <div class="mb-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'volunteer_list' %}" class="text-decoration-none">Volunteers</a></li>
                <li class="breadcrumb-item active" aria-current="page">{% if volunteer %}{{ volunteer.first_name }} {{ volunteer.last_name }}{% else %}Add New Volunteer{% endif %}</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between align-items-center">
            <h1 class="h2 mb-0">{% if volunteer %}{{ volunteer.first_name }} {{ volunteer.last_name }}{% else %}New Volunteer{% endif %}</h1>
            {% if volunteer %}
            <form action="{% url 'volunteer_delete' volunteer.id %}" method="POST" onsubmit="return confirm('Are you sure you want to delete this volunteer?')">
                {% csrf_token %}
                <button type="submit" class="btn btn-outline-danger btn-sm">Delete Volunteer</button>
            </form>
            {% endif %}
        </div>
    </div>

    <div class="row g-4">
        <!-- Volunteer Info & Edit Form -->
        <div class="col-lg-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4 p-md-5">
                    <h5 class="card-title fw-bold mb-4">Volunteer Information</h5>
                    <form action="{% if volunteer %}{% url 'volunteer_detail' volunteer.id %}{% else %}{% url 'volunteer_add' %}{% endif %}" method="POST" id="volunteerForm">
                        {% csrf_token %}
                        <div class="row g-4">
                            <div class="col-md-6">
                                <label for="{{ form.first_name.id_for_label }}" class="form-label small text-muted text-uppercase fw-bold">First Name</label>
                                {{ form.first_name }}
                            </div>
                            <div class="col-md-6">
                                <label for="{{ form.last_name.id_for_label }}" class="form-label small text-muted text-uppercase fw-bold">Last Name</label>
                                {{ form.last_name }}
                            </div>
                            <div class="col-md-6">
                                <label for="{{ form.email.id_for_label }}" class="form-label small text-muted text-uppercase fw-bold">Email Address</label>
                                {{ form.email }}
                            </div>
                            <div class="col-md-6">
                                <div class="d-flex justify-content-between align-items-center">
                                    <label for="{{ form.phone.id_for_label }}" class="form-label small text-muted text-uppercase fw-bold mb-1">Phone Number</label>
                                    {% if volunteer.phone %}
                                    <div class="mb-1">
                                        <a href="tel:{{ volunteer.phone }}" class="text-primary me-2" title="Call"><i class="bi bi-telephone"></i></a>
                                        <a href="sms:{{ volunteer.phone }}" class="text-secondary" title="Text"><i class="bi bi-chat-dots"></i></a>
                                    </div>
                                    {% endif %}
                                </div>
                                {{ form.phone }}
                            </div>
                            <div class="col-12">
                                <div class="form-check form-switch py-2">
                                    {{ form.is_default_caller }}
                                    <label class="form-check-label fw-bold text-muted text-uppercase small" for="{{ form.is_default_caller.id_for_label }}">
                                        Default Caller for Queue
                                    </label>
                                    <div class="form-text">If enabled, this volunteer will be the default assigned person for new call queue entries.</div>
                                </div>
                            </div>
                            <div class="col-12 mt-4">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <label for="{{ form.interests.id_for_label }}" class="form-label small text-muted text-uppercase fw-bold mb-0">Interests</label>
                                    <div>
                                        <button type="button" class="btn btn-sm btn-link text-decoration-none py-0 me-2" data-bs-toggle="modal" data-bs-target="#manageInterestsModal">
                                            <small>Manage Types</small>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-outline-primary py-0" data-bs-toggle="modal" data-bs-target="#addInterestModal">
                                            <small>+ Add New Type</small>
                                        </button>
                                    </div>
                                </div>
                                <div class="select2-container-wrapper">
                                    {{ form.interests }}
                                </div>
                                <div class="form-text small text-muted mt-2">Search and select multiple interest types for this volunteer.</div>
                            </div>
                            <div class="col-12">
                                <label for="{{ form.notes.id_for_label }}" class="form-label small text-muted text-uppercase fw-bold">Notes</label>
                                {{ form.notes }}
                            </div>
                        </div>
                        <div class="mt-5 pt-4 border-top text-end">
                            <a href="{% url 'volunteer_list' %}" class="btn btn-outline-secondary px-4 me-2">Cancel</a>
                            <button type="submit" class="btn btn-primary px-4">{% if volunteer %}Save Changes{% else %}Create Volunteer{% endif %}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        {% if volunteer %}
        <!-- Event Assignments -->
        <div class="col-lg-12 mt-4">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-0 py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold">Event Assignments</h5>
                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#assignEventModal">
                        + Assign Event
                    </button>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0 align-middle">
                        <thead class="bg-light">
                            <tr>
                                <th class="ps-4">Event</th>
                                <th>Role</th>
                                <th class="pe-4 text-end">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for assignment in assignments %}
                            <tr>
                                <td class="ps-4">
                                    <a href="{% url 'event_detail' assignment.event.id %}" class="fw-semibold text-primary text-decoration-none">
                                        {{ assignment.event.name|default:assignment.event.event_type }}
                                    </a>
                                    <div class="small text-muted">{{ assignment.event.date|date:"M d, Y" }}</div>
                                </td>
                                <td>{{ assignment.role_type|default:"Assigned" }}</td>
                                <td class="pe-4 text-end">
                                    <form action="{% url 'volunteer_remove_event' assignment.id %}" method="POST" onsubmit="return confirm('Remove this assignment?')">
                                        {% csrf_token %}
                                        <button type="submit" class="btn btn-sm btn-link text-danger p-0">Remove</button>
                                    </form>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="3" class="text-center py-5 text-muted">
                                    No events assigned yet.
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Add Interest Modal -->
<div class="modal fade" id="addInterestModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0 pb-0">
                <h6 class="modal-title fw-bold">New Interest Type</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="text" id="newInterestName" class="form-control" placeholder="e.g. Phone Banking">
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" id="saveInterestBtn" class="btn btn-sm btn-primary">Add</button>
            </div>
        </div>
    </div>
</div>

<!-- Manage Interests Modal -->
<div class="modal fade" id="manageInterestsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0 bg-light">
                <h5 class="modal-title fw-bold">Manage Interest Types</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="small text-muted mb-3">Deleting an interest type will remove it from all volunteers in the campaign.</p>
                <div class="list-group list-group-flush" id="manageInterestsList">
                    {% for interest in form.interests.field.queryset %}
                    <div class="list-group-item d-flex justify-content-between align-items-center px-0 interest-manage-item" data-id="{{ interest.id }}">
                        <span>{{ interest.name }}</span>
                        <button type="button" class="btn btn-sm btn-outline-danger border-0 delete-interest-btn" data-id="{{ interest.id }}">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                    {% endfor %}
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

{% if volunteer %}
<!-- Assign Event Modal -->
<div class="modal fade" id="assignEventModal" tabindex="-1" aria-labelledby="assignEventModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0 bg-primary text-white">
                <h5 class="modal-title fw-bold" id="assignEventModalLabel">Assign Volunteer to Event</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{% url 'volunteer_assign_event' volunteer.id %}" method="POST">
                {% csrf_token %}
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label for="{{ assign_form.event.id_for_label }}" class="form-label fw-bold">Select Event</label>
                        {{ assign_form.event }}
                    </div>
                    <div class="mb-0">
                        <label for="{{ assign_form.role_type.id_for_label }}" class="form-label fw-bold">Role/Task</label>
                        {{ assign_form.role_type }}
                        <div class="form-text">e.g., Phone Banker, Door knocker, Registration desk</div>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary px-4">Assign Event</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script src="{% static 'admin/js/vendor/select2/select2.full.min.js' %}"></script>
<script>
$(document).ready(function() {
    const $interestsSelect = $('#id_interests');
    
    // Initialize Select2
    $interestsSelect.select2({
        placeholder: "Select interests...",
        allowClear: true,
        multiple: true,
        width: '100%'
    });

    const saveInterestBtn = document.getElementById('saveInterestBtn');
    const newInterestNameInput = document.getElementById('newInterestName');
    const manageInterestsList = document.getElementById('manageInterestsList');

    if (saveInterestBtn) {
        saveInterestBtn.addEventListener('click', function() {
            const name = newInterestNameInput.value.trim();
            if (!name) return;

            const formData = new FormData();
            formData.append('name', name);
            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

            fetch('{% url "interest_add" %}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Add to Select2
                    const newOption = new Option(data.name, data.id, false, false);
                    $interestsSelect.append(newOption).trigger('change');
                    
                    // Add to manage list
                    const item = document.createElement('div');
                    item.className = 'list-group-item d-flex justify-content-between align-items-center px-0 interest-manage-item';
                    item.dataset.id = data.id;
                    item.innerHTML = `
                        <span>${data.name}</span>
                        <button type="button" class="btn btn-sm btn-outline-danger border-0 delete-interest-btn" data-id="${data.id}">
                            <i class="bi bi-trash"></i>
                        </button>
                    `;
                    manageInterestsList.appendChild(item);
                    
                    // Close modal and reset input
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addInterestModal'));
                    modal.hide();
                    newInterestNameInput.value = '';
                    
                    // Re-bind delete events
                    bindDeleteEvents();
                } else {
                    alert(data.error || 'Error adding interest.');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred.');
            });
        });
    }

    function bindDeleteEvents() {
        document.querySelectorAll('.delete-interest-btn').forEach(btn => {
            btn.onclick = function() {
                const id = this.dataset.id;
                if (!confirm('Are you sure you want to delete this interest type from the campaign? This will remove it from all volunteers.')) {
                    return;
                }

                const formData = new FormData();
                formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

                fetch(`/interests/${id}/delete/`, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Remove from Select2
                        $interestsSelect.find(`option[value="${id}"]`).remove();
                        $interestsSelect.trigger('change');
                        
                        // Remove from manage list
                        const item = document.querySelector(`.interest-manage-item[data-id="${id}"]`);
                        if (item) item.remove();
                    } else {
                        alert(data.error || 'Error deleting interest.');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred.');
                });
            };
        });
    }

    bindDeleteEvents();
});
</script>
{% endblock %}