{% extends 'portal_base.html' %}
{% load static i18n crispy_forms_tags %}

{% block title %}{% trans "Persons List" %} - ATS{% endblock %}
{% block customCSS %}
<style>
   :root {
        --kaauh-teal: #00636e;
        --kaauh-teal-dark: #004a53;
        --kaauh-border: #eaeff3;
        --kaauh-primary-text: #343a40;
        --kaauh-success: #28a745;
        --kaauh-info: #17a2b8;
        --kaauh-danger: #dc3545;
        --kaauh-warning: #ffc107;
    }

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

    .btn-main-action {
        background-color: var(--kaauh-teal);
        border-color: var(--kaauh-teal);
        color: white;
        font-weight: 600;
        transition: all 0.2s ease;
    }
    .btn-main-action:hover {
        background-color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-teal-dark);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }

    .person-row:hover {
        background-color: #f8f9fa;
        cursor: pointer;
    }

    .stage-badge {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        border-radius: 0.375rem;
        font-weight: 500;
    }

    .search-form {
        background-color: white;
        border: 1px solid var(--kaauh-border);
        border-radius: 0.5rem;
        padding: 1rem;
        margin-bottom: 1.5rem;
    }
</style>
{% endblock%}

{% block content %}
<div class="container-fluid py-4 persons-list">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="px-2 py-2">
            <h1 class="h3 mb-1" style="color: var(--kaauh-teal-dark); font-weight: 700;">
                <i class="fas fa-users me-2"></i>
                {% trans "All Applicants" %}
            </h1>
            <p class="text-muted mb-0">
                {% trans "All applicants who come through" %} {{ agency.name }}
            </p>
        </div>
        <div>
	            <!-- Add Person Button -->
            <button type="button" class="btn btn-main-action" data-bs-toggle="modal" data-bs-target="#personModal">
                <i class="fas fa-plus me-1"></i> {% trans "Add New Applicant" %}
            </button>
	        </div>
    </div>

    <!-- Search and Filter Section -->
    <div class="kaauh-card shadow-sm mb-4">
        <div class="card-body">
            <form method="get" class="search-form">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label for="search" class="form-label fw-semibold">
                            <i class="fas fa-search me-1"></i>{% trans "Search" %}
                        </label>
                        <input type="text"
                               class="form-control"
                               id="search"
                               name="q"
                               value="{{ search_query }}"
                               placeholder="{% trans 'Search by name, email, phone, or job title...' %}">
                    </div>
                    <div class="col-md-3">
                        <label for="stage" class="form-label fw-semibold">
                            <i class="fas fa-filter me-1"></i>{% trans "Stage" %}
                        </label>
                        <select class="form-select" id="stage" name="stage">
                            <option value="">{% trans "All Stages" %}</option>
                            {% for stage_value, stage_label in stage_choices %}
                                <option value="{{ stage_value }}"
                                        {% if stage_filter == stage_value %}selected{% endif %}>
                                    {{ stage_label }}
                                </option>
                            {% endfor %}
                        </select>
                    </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-search me-1"></i> {% trans "Search" %}
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Results Summary -->
    <div class="row mb-3">
        <div class="col-md-6">
            <div class="kaauh-card shadow-sm h-100 p-3">
                <div class="card-body text-center">
                    <div class="text-info mb-2">
                        <i class="fas fa-users fa-2x"></i>
                    </div>
                    <h4 class="card-title">{{ total_persons }}</h4>
                    <p class="card-text text-muted">{% trans "Total Persons" %}</p>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="kaauh-card shadow-sm h-100 p-3">
                <div class="card-body text-center">
                    <div class="text-success mb-2">
                        <i class="fas fa-check-circle fa-2x"></i>
                    </div>
                    <h4 class="card-title">{{ page_obj|length }}</h4>
                    <p class="card-text text-muted">{% trans "Showing on this page" %}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Persons Table -->
    <div class="kaauh-card shadow-sm">
        <div class="card-body p-0">
            {% if page_obj %}
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">{% trans "Name" %}</th>
                                <th scope="col">{% trans "Email" %}</th>
                                <th scope="col">{% trans "Phone" %}</th>
                                <th scope="col">{% trans "Job" %}</th>
                                <th scope="col">{% trans "Stage" %}</th>
                                <th scope="col">{% trans "Applied Date" %}</th>
                                <th scope="col" class="text-center">{% trans "Actions" %}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for person in page_obj %}
                                <tr class="person-row">
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="rounded-circle bg-primary-theme text-white d-flex align-items-center justify-content-center me-2"
                                                 style="width: 32px; height: 32px; font-size: 14px; font-weight: 600;">
                                                {{ person.first_name|first|upper }}{{ person.last_name|first|upper }}
                                            </div>
                                            <div>
                                                <div class="fw-semibold">{{ person.first_name }} {{ person.last_name }}</div>
                                                {% if person.address %}
                                                    <small class="text-muted">{{ person.address|truncatechars:50 }}</small>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <a href="mailto:{{ person.email }}" class="text-decoration-none text-dark">
                                            {{ person.email }}
                                        </a>
                                    </td>
                                    <td>{{ person.phone|default:"-" }}</td>
                                    <td>
                                        <span class="badge bg-light text-dark">
                                            {{ person.job.title|truncatechars:30 }}
                                        </span>
                                    </td>
                                    <td>
                                        {% with stage_class=person.stage|lower %}
                                            <span class="stage-badge
                                                {% if stage_class == 'applied' %}bg-secondary{% endif %}
                                                {% if stage_class == 'exam' %}bg-info{% endif %}
                                                {% if stage_class == 'interview' %}bg-warning{% endif %}
                                                {% if stage_class == 'offer' %}bg-success{% endif %}
                                                {% if stage_class == 'hired' %}bg-primary{% endif %}
                                                {% if stage_class == 'rejected' %}bg-danger{% endif %}
                                                text-white">
                                                {{ person.get_stage_display }}
                                            </span>
                                        {% endwith %}
                                    </td>
                                    <td>{{ person.created_at|date:"Y-m-d" }}</td>
                                    <td class="text-center">
                                        <div class="btn-group" role="group">
                                            <a href="{% url 'candidate_detail' person.slug %}"
                                               class="btn btn-sm btn-outline-primary"
                                               title="{% trans 'View Details' %}">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-secondary"
                                                    title="{% trans 'Edit Person' %}"
                                                    onclick="editPerson({{ person.id }})">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">{% trans "No persons found" %}</h5>
                    <p class="text-muted">
                        {% if search_query or stage_filter %}
                            {% trans "Try adjusting your search or filter criteria." %}
                        {% else %}
                            {% trans "No persons have been added yet." %}
                        {% endif %}
                    </p>
                    {% if not search_query and not stage_filter and agency.assignments.exists %}
                        <a href="{% url 'agency_portal_submit_candidate_page' agency.assignments.first.slug %}"
                           class="btn btn-main-action">
                            <i class="fas fa-user-plus me-1"></i> {% trans "Add First Person" %}
                        </a>
                    {% endif %}
                </div>
            {% endif %}
        </div>
    </div>

    <!-- Pagination -->
    {% if page_obj.has_other_pages %}
        <nav aria-label="{% trans 'Persons pagination' %}" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page=1{% if search_query %}&q={{ search_query }}{% endif %}{% if stage_filter %}&stage={{ stage_filter }}{% endif %}">
                            <i class="fas fa-angle-double-left"></i>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&q={{ search_query }}{% endif %}{% if stage_filter %}&stage={{ stage_filter }}{% endif %}">
                            <i class="fas fa-angle-left"></i>
                        </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">{{ 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 %}&q={{ search_query }}{% endif %}{% if stage_filter %}&stage={{ stage_filter }}{% 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 %}&q={{ search_query }}{% endif %}{% if stage_filter %}&stage={{ stage_filter }}{% endif %}">
                            <i class="fas fa-angle-right"></i>
                        </a>
                    </li>
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if search_query %}&q={{ search_query }}{% endif %}{% if stage_filter %}&stage={{ stage_filter }}{% endif %}">
                            <i class="fas fa-angle-double-right"></i>
                        </a>
                    </li>
                {% endif %}
            </ul>
        </nav>
    {% endif %}
</div>
<!-- Person Modal -->
<div class="modal fade modal-lg" id="personModal" tabindex="-1" aria-labelledby="personModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="personModalLabel">
                    <i class="fas fa-users me-2"></i>
                    {% trans "Applicant Details" %}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="personModalBody">
                <form id="person_form" hx-post="{% url 'person_create' %}" hx-vals='{"view":"portal","agency":"{{ agency.slug }}"}' hx-select=".persons-list" hx-target=".persons-list" hx-swap="outerHTML"
                hx-on:afterRequest="$('#personModal').modal('hide')">
                    {% csrf_token %}
                    <div class="row g-4">
                        <div class="col-md-4">
                            {{ person_form.first_name|as_crispy_field }}
                        </div>
                        <div class="col-md-4">
                            {{ person_form.middle_name|as_crispy_field }}
                        </div>
                    <div class="col-md-4">
                        {{ person_form.last_name|as_crispy_field }}
                    </div>
                </div>
                <div class="row g-4">
                    <div class="col-md-6">
                        {{ person_form.email|as_crispy_field }}
                    </div>
                    <div class="col-md-6">
                        {{ person_form.phone|as_crispy_field }}
                    </div>
                </div>
                <div class="row g-4">
                    <div class="col-md-6">
                        {{ person_form.date_of_birth|as_crispy_field }}
                    </div>
                    <div class="col-md-6">
                        {{ person_form.nationality|as_crispy_field }}
                    </div>
                </div>
                <div class="row g-4">
                    <div class="col-12">
                        {{ person_form.address|as_crispy_field }}
                    </div>
                </div>
            </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-main-action" type="submit" form="person_form">{% trans "Save" %}</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    {% trans "Close" %}
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function openPersonModal(personId, personName) {
    const modal = new bootstrap.Modal(document.getElementById('personModal'));
    document.getElementById('person-modal-text').innerHTML = `<strong>${personName}</strong> (ID: ${personId})`;
    modal.show();
}
</script>
<script>
function editPerson(personId) {
    // Placeholder for edit functionality
    // This would typically open a modal or navigate to edit page
    console.log('Edit person:', personId);
    // For now, you can redirect to a placeholder edit URL
    // window.location.href = `/portal/candidates/${personId}/edit/`;
}

// Auto-submit form on filter change
document.getElementById('stage').addEventListener('change', function() {
    this.form.submit();
});

// Add row click functionality
document.querySelectorAll('.person-row').forEach(row => {
    row.addEventListener('click', function(e) {
        // Don't trigger if clicking on buttons or links
        if (e.target.closest('a, button')) {
            return;
        }

        // Find the view details button and click it
        const viewBtn = this.querySelector('a[title*="View"]');
        if (viewBtn) {
            viewBtn.click();
        }
    });
});
</script>

{% endblock %}
