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

{% block title %}{{ job.title }} - Applicants{% endblock %}

{% block customCSS %}
<style>
    /* ================================================= */
    /* THEME VARIABLES AND GLOBAL STYLES */
    /* ================================================= */
    :root {
        --kaauh-teal: #00636e; /* Primary */
        --kaauh-teal-dark: #004a53;
        --kaauh-border: #eaeff3;
        --kaauh-primary-text: #343a40;
    }

    /* Primary Color Overrides */
    .text-primary { color: var(--kaauh-teal) !important; }
    .text-info { color: #17a2b8 !important; }
    .text-success { color: #28a745 !important; }
    .text-secondary { color: #6c757d !important; }
    .bg-primary { background-color: var(--kaauh-teal) !important; }
    .bg-info { background-color: #17a2b8 !important; }
    .bg-success { background-color: #28a745 !important; }
    .bg-secondary { background-color: #6c757d !important; }
    .bg-warning { background-color: #ffc107 !important; }

    /* Card enhancements */
    .card {
        border: 1px solid var(--kaauh-border);
        border-radius: 0.75rem;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0,0,0,0.06);
        background-color: white;
    }

    .card-header {
        font-weight: 600;
        padding: 1rem 1.25rem;
        background-color: #f8f9fa; /* Light background */
        border-bottom: 1px solid var(--kaauh-border);
    }
    
    /* Main Action Button Style */
    .btn-main-action {
        background-color: var(--kaauh-teal);
        border-color: var(--kaauh-teal);
        color: white;
        font-weight: 600;
        padding: 0.6rem 1.2rem;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        justify-content: center;
        text-align: center;
    }
    .btn-main-action:hover {
        background-color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-teal-dark);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    
    /* Secondary outline button */
    .btn-outline-secondary {
        color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-teal);
        font-weight: 500;
    }
    .btn-outline-secondary:hover {
        background-color: var(--kaauh-teal-dark);
        color: white;
        border-color: var(--kaauh-teal-dark);
    }

    /* Table styling */
    .table-hover tbody tr:hover {
        background-color: #f3f7f9;
        cursor: pointer;
    }
    .table thead th {
        color: #6c757d;
        font-weight: 600;
        border-bottom: 2px solid var(--kaauh-border);
    }

    /* Card view specific styling */
    .card-view .card-header {
        background-color: var(--kaauh-teal);
        color: white;
    }
    .card-view .card-footer {
        background-color: #f8f9fa;
        border-top: 1px solid var(--kaauh-border);
    }
    
    .status-badge {
        font-size: 0.9rem;
        padding: 0.4em 0.8em;
        border-radius: 0.4rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.7px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-1 fw-bold">
                <a href="{% url 'job_detail' job.slug %}" class="text-primary text-decoration-none">
                    <i class="fas fa-arrow-left me-2"></i>
                </a>
                {% trans "Applicants for" %} "{{ job.title }}"
            </h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 small">
                    <li class="breadcrumb-item"><a href="{% url 'dashboard' %}" class="text-secondary">{% trans "Dashboard" %}</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'job_list' %}" class="text-secondary">{% trans "Jobs" %}</a></li>
                    <li class="breadcrumb-item"><a href="{% url 'job_detail' job.slug %}" class="text-secondary">{{ job.title }}</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{% trans "Applicants" %}</li>
                </ol>
            </nav>
        </div>
        <div>
            <a href="{% url 'candidate_create_for_job' job.slug %}" class="btn btn-main-action">
                <i class="fas fa-user-plus"></i> {% trans "Add New Applicant" %}
            </a>
        </div>
    </div>

    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h5 class="fw-bold mb-3 text-primary">{{ job.title }}</h5>
                    <div class="row small text-secondary g-2">
                        <div class="col-md-6">
                            <i class="fas fa-building me-2 text-info"></i> <strong>{% trans "Department:" %}</strong> {{ job.department|default:"N/A" }}
                        </div>
                        <div class="col-md-6">
                            <i class="fas fa-map-pin me-2 text-info"></i> <strong>{% trans "Location:" %}</strong> {{ job.get_location_display }}
                        </div>
                        <div class="col-md-6">
                            <i class="fas fa-briefcase me-2 text-info"></i> <strong>{% trans "Job Type:" %}</strong> {{ job.get_job_type_display }}
                        </div>
                        <div class="col-md-6">
                            <i class="fas fa-globe me-2 text-info"></i> <strong>{% trans "Workplace:" %}</strong> {{ job.get_workplace_type_display }}
                        </div>
                    </div>
                </div>
                <div class="col-md-4 text-end border-start ps-4">
                    <span class="badge status-badge mb-2 bg-{% if job.status == 'ACTIVE' %}success{% elif job.status == 'DRAFT' or job.status == 'ARCHIVED' %}secondary{% elif job.status == 'CLOSED' %}warning{% else %}danger{% endif %}">
                        {{ job.get_status_display }}
                    </span>
                    {% if candidates %}
                        <div class="mt-2">
                            <small class="text-muted d-block">{% trans "Total Applicants" %}:</small>
                            <h3 class="text-primary fw-bold mb-0">{{ candidates.count }}</h3>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form method="get" class="row g-3">
                <div class="col-md-6">
                    <label for="search" class="form-label small text-muted">{% trans "Search Applicants" %}</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search text-primary"></i></span>
                        <input type="text" class="form-control" id="search" name="search"
                               placeholder="{% trans 'Search by name, email, phone, or stage...' %}"
                               value="{{ search_query }}">
                    </div>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-main-action w-100">
                        <i class="fas fa-filter"></i> {% trans "Filter Results" %}
                    </button>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <a href="{% url 'job_candidates_list' job.slug %}" class="btn btn-outline-secondary w-100">
                        <i class="fas fa-times"></i> {% trans "Clear Filters" %}
                    </a>
                </div>
            </form>
        </div>
    </div>

    {% if candidates %}
        <div id="job-candidates-list">
            {# View Switcher (Assuming this template is customized to match the new UI style) #}
            {% include "includes/_list_view_switcher.html" with list_id="job-candidates-list" %}

            {# Table View (Default) #}
            <div class="table-view active">
                <div class="card shadow-sm">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">{% trans "Applicants" %} ({{ candidates.count }})</h5>
                            <div class="d-flex gap-2">
                                <select class="form-select form-select-sm" style="width: auto;" onchange="window.location.href='?stage='+this.value+'&search={{ search_query }}'">
                                    <option value="">{% trans "All Stages" %}</option>
                                    <option value="Applied" {% if request.GET.stage == 'Applied' %}selected{% endif %}>{% trans "Applied" %}</option>
                                    <option value="Exam" {% if request.GET.stage == 'Exam' %}selected{% endif %}>{% trans "Exam" %}</option>
                                    <option value="Interview" {% if request.GET.stage == 'Interview' %}selected{% endif %}>{% trans "Interview" %}</option>
                                    <option value="Offer" {% if request.GET.stage == 'Offer' %}selected{% endif %}>{% trans "Offer" %}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead>
                                <tr>
                                    <th scope="col" class="ps-3">
                                        <input type="checkbox" class="form-check-input" id="selectAll">
                                    </th>
                                    <th scope="col">{% trans "Name" %}</th>
                                    <th scope="col">{% trans "Email" %}</th>
                                    <th scope="col">{% trans "Phone" %}</th>
                                    <th scope="col">{% trans "Stage" %}</th>
                                    <th scope="col">{% trans "Applied Date" %}</th>
                                    <th scope="col" class="text-center pe-3">{% trans "Actions" %}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for candidate in candidates %}
                                    <tr>
                                        <td class="ps-3">
                                            <input type="checkbox" class="form-check-input candidate-checkbox" value="{{ candidate.slug }}">
                                        </td>
                                        <td>
                                            <strong class="text-primary">{{ candidate.first_name }} {{ candidate.last_name }}</strong>
                                        </td>
                                        <td>{{ candidate.email }}</td>
                                        <td>{{ candidate.phone|default:"-" }}</td>
                                        <td>
                                            <span class="badge bg-{% if candidate.stage == 'Applied' %}primary{% elif candidate.stage == 'Exam' %}info{% elif candidate.stage == 'Interview' %}warning text-dark{% elif candidate.stage == 'Offer' %}success{% else %}secondary{% endif %}">
                                                {{ candidate.stage }}
                                            </span>
                                        </td>
                                        <td class="text-secondary small">{{ candidate.created_at|date:"M d, Y" }}</td>
                                        <td class="text-center pe-3">
                                            <div class="btn-group" role="group">
                                                <a href="{% url 'candidate_detail' candidate.slug %}" class="btn btn-outline-secondary btn-sm" title="{% trans 'View' %}">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                {% if user.is_staff %}
                                                    <a href="{% url 'candidate_update' candidate.slug %}" class="btn btn-outline-secondary btn-sm" title="{% trans 'Edit' %}">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <button type="button" class="btn btn-outline-danger btn-sm" title="{% trans 'Delete' %}"
                                                            data-bs-toggle="modal" data-bs-target="#deleteModal"
                                                            data-delete-url="{% url 'candidate_delete' candidate.slug %}"
                                                            data-item-name="{{ candidate.first_name }} {{ candidate.last_name }}">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                {% endif %}
                                            </div>
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>

                    <div class="card-footer d-flex justify-content-between align-items-center bg-light">
                        <div class="d-flex align-items-center">
                            <span class="me-3 small text-muted">{% trans "Selected" %}: <strong id="selectedCount">0</strong></span>
                            <button class="btn btn-sm btn-outline-secondary me-2" onclick="bulkAction('Interview')"
                                    {% if not user.is_staff %}disabled{% endif %}>
                                <i class="fas fa-comments me-1"></i> {% trans "Mark Interview" %}
                            </button>
                            <button class="btn btn-sm btn-main-action" onclick="bulkAction('Offer')"
                                    {% if not user.is_staff %}disabled{% endif %}>
                                <i class="fas fa-handshake me-1"></i> {% trans "Mark Offer" %}
                            </button>
                        </div>

                        {% if is_paginated %}
                            <nav aria-label="Page navigation">
                                <ul class="pagination pagination-sm mb-0">
                                    {% if page_obj.has_previous %}
                                        <li class="page-item">
                                            <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}" aria-label="Previous">
                                                <span aria-hidden="true">&laquo;</span>
                                            </a>
                                        </li>
                                    {% endif %}

                                    {% for num in page_obj.paginator.page_range %}
                                        {% if page_obj.number == num %}
                                            <li class="page-item active"><span class="page-link bg-primary border-primary">{{ num }}</span></li>
                                        {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                            <li class="page-item">
                                                <a class="page-link" href="?page={{ num }}{% if search_query %}&search={{ search_query }}{% endif %}">{{ num }}</a>
                                            </li>
                                        {% endif %}
                                    {% endfor %}

                                    {% if page_obj.has_next %}
                                        <li class="page-item">
                                            <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}" aria-label="Next">
                                                <span aria-hidden="true">&raquo;</span>
                                            </a>
                                        </li>
                                    {% endif %}
                                </ul>
                            </nav>
                        {% endif %}
                    </div>
                </div>
            </div>

            {# Card View #}
            <div class="card-view">
                <div class="row g-4">
                    {% for candidate in candidates %}
                        <div class="col-md-6 col-lg-4">
                            <div class="card h-100 shadow-sm">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <div>
                                        <h5 class="h5 mb-1 text-white">{{ candidate.first_name }} {{ candidate.last_name }}</h5>
                                        <small class="text-white-50">{{ candidate.email }}</small>
                                    </div>
                                    <span class="badge status-badge bg-{% if candidate.stage == 'Applied' %}bg-secondary{% elif candidate.stage == 'Exam' %}bg-info{% elif candidate.stage == 'Interview' %}bg-warning text-dark{% elif candidate.stage == 'Offer' %}bg-success{% else %}bg-secondary{% endif %}">
                                        {{ candidate.stage }}
                                    </span>
                                </div>
                                <div class="card-body small text-secondary">
                                    <p class="mb-2">
                                        <i class="fas fa-phone me-2 text-primary"></i> <strong>{% trans "Phone" %}:</strong> {{ candidate.phone|default:"N/A" }}
                                    </p>
                                    <p class="mb-0">
                                        <i class="fas fa-calendar-alt me-2 text-primary"></i> <strong>{% trans "Applied Date" %}:</strong> {{ candidate.created_at|date:"M d, Y" }}
                                    </p>
                                </div>
                                <div class="card-footer">
                                    <div class="d-flex gap-2">
                                        <a href="{% url 'candidate_detail' candidate.slug %}" class="btn btn-outline-secondary w-100">
                                            <i class="fas fa-eye"></i> {% trans "View Profile" %}
                                        </a>
                                        {% if user.is_staff %}
                                            <div class="btn-group" role="group">
                                                <a href="{% url 'candidate_update' candidate.slug %}" class="btn btn-sm btn-outline-secondary" title="{% trans 'Edit' %}">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <button type="button" class="btn btn-outline-danger btn-sm" title="{% trans 'Delete' %}"
                                                        data-bs-toggle="modal" data-bs-target="#deleteModal"
                                                        data-delete-url="{% url 'candidate_delete' candidate.slug %}"
                                                        data-item-name="{{ candidate.first_name }} {{ candidate.last_name }}">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    {% else %}
        <div class="card shadow-sm">
            <div class="text-center py-5">
                <i class="fas fa-user-slash fa-3x text-muted mb-3"></i>
                <h4 class="text-muted">{% trans "No applicants found" %}</h4>
                <p class="text-secondary">{% trans "There are no candidates who have applied for this position yet." %}</p>
                <a href="{% url 'candidate_create_for_job' job.slug %}" class="btn btn-main-action mt-3">
                    <i class="fas fa-user-plus"></i> {% trans "Add First Applicant" %}
                </a>
            </div>
        </div>
    {% endif %}

    {% include "includes/delete_modal.html" %}
</div>
{% endblock %}

{% block extra_js %}
<script>
// Select all checkbox functionality
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.candidate-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
    updateSelectedCount();
});

// Individual checkbox change
document.querySelectorAll('.candidate-checkbox').forEach(checkbox => {
    checkbox.addEventListener('change', updateSelectedCount);
});

function updateSelectedCount() {
    const checkedBoxes = document.querySelectorAll('.candidate-checkbox:checked');
    document.getElementById('selectedCount').textContent = checkedBoxes.length;
}

function bulkAction(stage) {
    const selectedCandidates = Array.from(document.querySelectorAll('.candidate-checkbox:checked'))
        .map(cb => cb.value);

    if (selectedCandidates.length === 0) {
        alert('Please select at least one candidate.');
        return;
    }

    if (confirm(`Mark ${selectedCandidates.length} candidate(s) as ${stage}?`)) {
        // Here you would typically make an AJAX request to update the candidates
        console.log('Updating candidates:', selectedCandidates, 'to stage:', stage);
        // For now, just show a message
        alert(`Bulk update functionality would mark ${selectedCandidates.length} candidates as ${stage}`);
        // After a successful AJAX request, you would likely reload the page or update the rows dynamically.
    }
}

// Bootstrap Delete Modal Fix for dynamically loaded data attributes
document.addEventListener('DOMContentLoaded', function () {
    const deleteModal = document.getElementById('deleteModal');
    if (deleteModal) {
        deleteModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const deleteUrl = button.getAttribute('data-delete-url');
            const itemName = button.getAttribute('data-item-name');
            
            const modalTitle = deleteModal.querySelector('.modal-title');
            const modalBody = deleteModal.querySelector('.modal-body p');
            const deleteForm = deleteModal.querySelector('form');

            modalTitle.textContent = `Delete ${itemName}`;
            modalBody.innerHTML = `Are you sure you want to permanently delete the applicant <strong>${itemName}</strong>? This action cannot be undone.`;
            deleteForm.action = deleteUrl;
        });
    }
});
</script>
{% endblock %}