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

{% block title %}- {{ job.title }} - ATS{% endblock %}
{% block customCSS %}
<style>
    /* KAAT-S UI Variables */
    :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;
    }

    /* Primary Color Overrides */
    .text-primary-theme { color: var(--kaauh-teal) !important; }
    .bg-primary-theme { background-color: var(--kaauh-teal) !important; }

    /* 1. Main Container & Card Styling */
    .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;
    }

    /* Dedicated style for the filter block */
    .filter-controls {
        background-color: #f8f9fa;
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 2rem;
        border: 1px solid var(--kaauh-border);
    }

    /* 2. Button Styling (Themed for Main Actions) */
    .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);
    }
    .btn-outline-secondary {
        color: var(--kaauh-teal-dark);
        border-color: var(--kaauh-teal);
    }
    .btn-outline-secondary:hover {
        background-color: var(--kaauh-teal-dark);
        color: white;
        border-color: var(--kaauh-teal-dark);
    }

    /* 3. Candidate Table Styling (Aligned with KAAT-S) */
    .candidate-table {
        table-layout: fixed;
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        background-color: white;
        border-radius: 0.5rem;
        overflow: hidden;
    }
    .candidate-table thead {
        background-color: var(--kaauh-border);
    }
    .candidate-table th {
        padding: 0.75rem 1rem;
        font-weight: 600;
        color: var(--kaauh-teal-dark);
        border-bottom: 2px solid var(--kaauh-teal);
        font-size: 0.9rem;
        vertical-align: middle;
    }
    .candidate-table td {
        padding: 0.75rem 1rem;
        border-bottom: 1px solid var(--kaauh-border);
        vertical-align: middle;
        font-size: 0.9rem;
    }
    .candidate-table tbody tr:hover {
        background-color: #f1f3f4;
    }
    .candidate-table thead th:nth-child(1) { width: 40px; }
    .candidate-table thead th:nth-child(4) { width: 10%; }
    .candidate-table thead th:nth-child(7) { width: 100px; }

    .candidate-name {
        font-weight: 600;
        color: var(--kaauh-primary-text);
    }
    .candidate-details {
        font-size: 0.8rem;
        color: #6c757d;
    }

    /* 4. Badges and Statuses */
    .ai-score-badge {
        background-color: var(--kaauh-teal-dark) !important;
        color: white;
        font-weight: 700;
        padding: 0.4em 0.8em;
        border-radius: 0.4rem;
    }
    .status-badge {
        font-size: 0.75rem;
        padding: 0.3em 0.7em;
        border-radius: 0.35rem;
        font-weight: 700;
    }
    .bg-applicant { background-color: #6c757d !important; color: white; }
    .bg-candidate { background-color: var(--kaauh-success) !important; color: white; }

    /* Stage Badges */
    .stage-badge {
        font-size: 0.75rem;
        padding: 0.25rem 0.6rem;
        border-radius: 0.3rem;
        font-weight: 600;
        display: inline-block;
        margin-bottom: 0.2rem;
    }
    .stage-Applied { background-color: #e9ecef; color: #495057; }
    .stage-Screening { background-color: var(--kaauh-info); color: white; }
    .stage-Exam { background-color: var(--kaauh-warning); color: #856404; }
    .stage-Interview { background-color: #17a2b8; color: white; }
    .stage-Offer { background-color: var(--kaauh-success); color: white; }
    .stage-Hired { background-color: #28a745; color: white; }

    /* Timeline specific container */
    .applicant-tracking-timeline {
        margin-bottom: 2rem;
    }

    /* Hired-specific styling */
    .hired-badge {
        background-color: #28a745 !important;
        color: white;
        font-weight: 700;
        padding: 0.5em 1em;
        border-radius: 0.5rem;
        font-size: 0.9rem;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .hired-date {
        font-size: 0.8rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    /* Success state styling */
    .success-header {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        padding: 1.5rem;
        border-radius: 0.75rem;
        margin-bottom: 2rem;
        text-align: center;
    }

    /* --- CUSTOM HEIGHT OPTIMIZATION (MAKING INPUTS/BUTTONS SMALLER) --- */
    .form-control-sm,
    .btn-sm {
        /* Reduce vertical padding even more than default Bootstrap 'sm' */
        padding-top: 0.2rem !important;
        padding-bottom: 0.2rem !important;
        /* Ensure a consistent, small height for both */
        height: 28px !important;
        font-size: 0.8rem !important; /* Slightly smaller font */
    }
</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" style="color: var(--kaauh-teal-dark); font-weight: 700;">
                <i class="fas fa-trophy me-2"></i>
                {% trans "Hired Candidates" %} - {{ job.title }}
            </h1>
            <h2 class="h5 text-muted mb-0">
                {% trans "Successfully Hired:" %} <span class="fw-bold">{{ candidates|length }}</span>
            </h2>
        </div>
        <div class="d-flex gap-2">
            <button type="button"
                    class="btn btn-main-action"
                    onclick="syncHiredCandidates()"
                    title="{% trans 'Sync hired candidates to external sources' %}">
                <i class="fas fa-sync me-1"></i> {% trans "Sync to Sources" %}
            </button>
            <a href="{% url 'export_candidates_csv' job.slug 'hired' %}"
               class="btn btn-outline-secondary"
               title="{% trans 'Export hired candidates to CSV' %}">
                <i class="fas fa-download me-1"></i> {% trans "Export CSV" %}
            </a>
            <a href="{% url 'job_detail' job.slug %}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i> {% trans "Back to Job" %}
            </a>
        </div>
    </div>

    <!-- Success Header -->
    <div class="success-header">
        <i class="fas fa-check-circle fa-3x mb-3"></i>
        <h3 class="mb-2">{% trans "Congratulations!" %}</h3>
        <p class="mb-0">{% trans "These candidates have successfully completed the hiring process and joined your team." %}</p>
    </div>

    <div class="applicant-tracking-timeline">
        {% include 'jobs/partials/applicant_tracking.html' %}
    </div>

    <div class="kaauh-card shadow-sm p-3">
         {% if candidates %}
            <div class="bulk-action-bar p-3 bg-light border-bottom">
                <form hx-boost="true" hx-include="#candidate-form" action="{% url 'candidate_update_status' job.slug %}" method="post" class="action-group">
                    {% csrf_token %}

                    {# MODIFIED: Using d-flex for horizontal alignment and align-items-end to align everything based on the baseline of the button/select #}
                    <div class="d-flex align-items-end gap-3">

                        {# Select Input Group #}
                        <div>
                            
                            <select name="mark_as" id="update_status" class="form-select form-select-sm" style="min-width: 150px;">
                                <option selected>
                                    ----------
                                </option>
                                <option value="Offer">
                                    {% trans "Offer Stage" %}
                                </option>
                                {# Include other options here, such as Interview, Offer, Rejected, etc. #}
                            </select>
                        </div>

                        {# Button #}
                        <button type="submit" class="btn btn-main-action btn-sm">
                            <i class="fas fa-arrow-right me-1"></i> {% trans "Change Stage" %}
                        </button>
                          {# email button#}
                          <button type="button" class="btn btn-outline-info btn-sm"
                                data-bs-toggle="modal"
                                hx-boost='true'
                                data-bs-target="#emailModal"
                                hx-get="{% url 'compose_candidate_email' job.slug %}"
                                hx-target="#emailModalBody"
                                hx-include="#candidate-form"
                                title="Email Participants">
                                <i class="fas fa-envelope"></i>
                        </button>

                    </div>
                </form>
            </div>
        {% endif %}

        <div class="table-responsive">
            <form id="candidate-form" action="{% url 'candidate_update_status' job.slug %}" method="get">
            {% csrf_token %}
            <table class="table candidate-table align-middle">
                <thead>
                    <tr>
                         <th style="width: 2%">
                            {% if candidates %}
                                <div class="form-check">
                                    <input
                                    type="checkbox" class="form-check-input" id="selectAllCheckbox">
                                </div>
                            {% endif %}
                        </th>
                        <th style="width: 15%"><i class="fas fa-user me-1"></i> {% trans "Name" %}</th>
                        <th style="width: 15%"><i class="fas fa-phone me-1"></i> {% trans "Contact" %}</th>
                        <th style="width: 15%"><i class="fas fa-briefcase me-1"></i> {% trans "Applied Position" %}</th>
                        <th class="text-center" style="width: 15%"><i class="fas fa-calendar-check me-1"></i> {% trans "Hired Date" %}</th>
                        <th class="text-center" style="width: 15%"><i class="fas fa-calendar-check me-1"></i> {% trans "Status" %}</th>
                        <th style="width: 15%"><i class="fas fa-cog me-1"></i> {% trans "Actions" %}</th>
                    </tr>
                </thead>
                <tbody>
                    {% for candidate in candidates %}
                    <tr>
                         <td>
                            <div class="form-check">
                                <input name="candidate_ids" value="{{ candidate.id }}" type="checkbox" class="form-check-input rowCheckbox" id="candidate-{{ candidate.id }}">
                            </div>

                        </td>
                        <td>
                            <div class="candidate-name">
                                {{ candidate.name }}
                            </div>
                        </td>
                        <td>
                            <div class="candidate-details">
                                <i class="fas fa-envelope me-1"></i> {{ candidate.email }}<br>
                                <i class="fas fa-phone me-1"></i> {{ candidate.phone }}
                            </div>
                        </td>
                        <td>
                            <div class="candidate-details">
                                <strong>{{ job.title }}</strong><br>
                                <small class="text-muted">{{ job.department }}</small>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="hired-date">
                                {% if candidate.offer_date %}
                                    <i class="fas fa-calendar me-1"></i>
                                    {{ candidate.offer_date|date:"M d, Y" }}
                                {% else %}
                                    <span class="text-muted">--</span>
                                {% endif %}
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="hired-badge mt-1">
                                    <i class="fas fa-check-circle"></i>
                                    {% trans "Hired" %}
                                </div>
                        </td>
                        <td>
                            <div class="btn-group" role="group">
                                <button type="button" class="btn btn-outline-secondary btn-sm"
                                    data-bs-toggle="modal"
                                    data-bs-target="#candidateviewModal"
                                    hx-get="{% url 'candidate_criteria_view_htmx' candidate.pk %}"
                                    hx-target="#candidateviewModalBody"
                                    title="View Profile">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <a href="{% url 'candidate_resume_template' candidate.slug %}"
                                   class="btn btn-outline-primary btn-sm"
                                   title="View Resume Template">
                                    <i class="fas fa-file-alt"></i>
                                </a>

                                
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </form>
            {% if not candidates %}
                <div class="alert alert-info text-center mt-3 mb-0" role="alert">
                    <i class="fas fa-info-circle me-1"></i>
                    {% trans "No candidates have been hired for this position yet." %}
                </div>
            {% endif %}
        </div>
    </div>

</div>

<div class="modal fade modal-xl" id="candidateviewModal" tabindex="-1" aria-labelledby="candidateviewModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content kaauh-card">
            <div class="modal-header" style="border-bottom: 1px solid var(--kaauh-border);">
                <h5 class="modal-title" id="candidateviewModalLabel" style="color: var(--kaauh-teal-dark);">
                    {% trans "Hired Candidate Details" %}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div id="candidateviewModalBody" class="modal-body">
                <div class="text-center py-5 text-muted">
                    <i class="fas fa-spinner fa-spin fa-2x"></i><br>
                    {% trans "Loading content..." %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Sync Results Modal -->
<div class="modal fade" id="syncResultsModal" tabindex="-1" aria-labelledby="syncResultsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content kaauh-card">
            <div class="modal-header" style="border-bottom: 1px solid var(--kaauh-border);">
                <h5 class="modal-title" id="syncResultsModalLabel" style="color: var(--kaauh-teal-dark);">
                    <i class="fas fa-sync me-2"></i>{% trans "Sync Results" %}
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div id="syncResultsModalBody" class="modal-body">
                <div class="text-center py-5 text-muted">
                    <i class="fas fa-spinner fa-spin fa-2x"></i><br>
                    {% trans "Syncing candidates..." %}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Close" %}</button>
            </div>
        </div>
    </div>
</div>


<!-- Email Modal -->
<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="emailModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content kaauh-card">
      <div class="modal-header" style="border-bottom: 1px solid var(--kaauh-border);">
        <h5 class="modal-title" id="emailModalLabel" style="color: var(--kaauh-teal-dark);">
          <i class="fas fa-envelope me-2"></i>{% trans "Compose Email" %}
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div id="emailModalBody" class="modal-body">
        <div class="text-center py-5 text-muted">
          <i class="fas fa-spinner fa-spin fa-2x"></i><br>
          {% trans "Loading email form..." %}
        
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block customJS %}
<script>
     document.addEventListener('DOMContentLoaded', function () {
        const selectAllCheckbox = document.getElementById('selectAllCheckbox');
        const rowCheckboxes = document.querySelectorAll('.rowCheckbox');

        if (selectAllCheckbox) {
            // Function to safely update the header checkbox state
            function updateSelectAllState() {
                const checkedCount = Array.from(rowCheckboxes).filter(cb => cb.checked).length;
                const totalCount = rowCheckboxes.length;

                if (checkedCount === 0) {
                    selectAllCheckbox.checked = false;
                    selectAllCheckbox.indeterminate = false;
                } else if (checkedCount === totalCount) {
                    selectAllCheckbox.checked = true;
                    selectAllCheckbox.indeterminate = false;
                } else {
                    selectAllCheckbox.checked = false;
                    selectAllCheckbox.indeterminate = true;
                }
            }

            // 1. Logic for the 'Select All' checkbox (Clicking it updates all rows)
            selectAllCheckbox.addEventListener('change', function () {
                const isChecked = selectAllCheckbox.checked;

                rowCheckboxes.forEach(checkbox => checkbox.removeEventListener('change', updateSelectAllState));

                rowCheckboxes.forEach(function (checkbox) {
                    checkbox.checked = isChecked;
                    checkbox.dispatchEvent(new Event('change', { bubbles: true }));
                });

                rowCheckboxes.forEach(checkbox => checkbox.addEventListener('change', updateSelectAllState));
                updateSelectAllState();
            });

            // 2. Logic to update 'Select All' state based on row checkboxes
            rowCheckboxes.forEach(function (checkbox) {
                checkbox.addEventListener('change', updateSelectAllState);
            });

            // Initial check to set the correct state on load (in case items are pre-checked)
            updateSelectAllState();
        }
    });

    function syncHiredCandidates() {
        const syncButton = document.querySelector('[onclick="syncHiredCandidates()"]');
        const modal = new bootstrap.Modal(document.getElementById('syncResultsModal'));

        // Show modal with loading state
        document.getElementById('syncResultsModalBody').innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <h5>{% trans "Syncing hired candidates..." %}</h5>
                <p class="text-muted">{% trans "Please wait while we sync candidates to external sources." %}</p>
            </div>
        `;

        modal.show();

        // Disable sync button during sync
        syncButton.disabled = true;
        syncButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> {% trans "Syncing..." %}';

        // Perform sync request
        fetch(`{% url 'sync_hired_candidates' job.slug %}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'queued') {
                // Task is queued, start polling for status
                console.log('Sync task queued with ID:', data.task_id);
                pollSyncStatus(data.task_id);
            } else if (data.status === 'success') {
                displaySyncResults(data.results);
            } else {
                displaySyncError(data.message);
            }
        })
        .catch(error => {
            console.error('Sync error:', error);
            displaySyncError('{% trans "An unexpected error occurred during sync." %}');
        })
        .finally(() => {
            // Re-enable sync button
            syncButton.disabled = false;
            syncButton.innerHTML = '<i class="fas fa-sync me-1"></i> {% trans "Sync to Sources" %}';
        });
    }

    function displaySyncResults(results) {
        const modalBody = document.getElementById('syncResultsModalBody');
        console.log('Sync results:', results);
        let html = '<div class="sync-results">';

        // Summary section
        html += `
            <div class="alert alert-info mb-4">
                <h6 class="alert-heading">{% trans "Sync Summary" %}</h6>
                <div class="row">
                    <div class="col-md-3">
                        <strong>{% trans "Total Sources:" %}</strong> ${results.source_results?.total_sources}
                    </div>
                    <div class="col-md-3">
                        <strong>{% trans "Successful:" %}</strong> <span class="text-success">${results.successful_syncs}</span>
                    </div>
                    <div class="col-md-3">
                        <strong>{% trans "Failed:" %}</strong> <span class="text-danger">${results.failed_syncs}</span>
                    </div>
                    <div class="col-md-3">
                        <strong>{% trans "Candidates Synced:" %}</strong> ${results.total_candidates}
                    </div>
                </div>
            </div>
        `;

        // Detailed results for each source
        if (results.sources && results.sources.length > 0) {
            html += '<h6 class="mb-3">{% trans "Source Details" %}</h6>';

            results.sources.forEach(source => {
                const statusClass = source.status === 'success' ? 'success' : 'danger';
                const statusIcon = source.status === 'success' ? 'check-circle' : 'exclamation-triangle';

                html += `
                    <div class="card mb-3">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <strong>${source.source_name}</strong>
                            <span class="badge bg-${statusClass}">
                                <i class="fas fa-${statusIcon} me-1"></i>
                                ${source.status.toUpperCase()}
                            </span>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <small class="text-muted">{% trans "Candidates Processed:" %}</small>
                                    <div class="fw-bold">${source.candidates_processed}</div>
                                </div>
                                <div class="col-md-6">
                                    <small class="text-muted">{% trans "Duration:" %}</small>
                                    <div class="fw-bold">${source.duration}</div>
                                </div>
                            </div>
                            ${source.message ? `<div class="mt-2"><small class="text-muted">{% trans "Message:" %}</small><div>${source.message}</div></div>` : ''}
                            ${source.error ? `<div class="mt-2 text-danger"><small>{% trans "Error:" %}</small><div>${source.error}</div></div>` : ''}
                        </div>
                    </div>
                `;
            });
        }

        html += '</div>';
        modalBody.innerHTML = html;
    }

    function pollSyncStatus(taskId) {
        console.log('Polling for sync status...');
        const pollInterval = setInterval(() => {
            fetch(`/sync/task/${taskId}/status/`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'completed') {
                    clearInterval(pollInterval);
                    displaySyncResults(data.result);
                } else if (data.status === 'failed') {
                    clearInterval(pollInterval);
                    displaySyncError(data.message || '{% trans "Sync task failed" %}');
                } else if (data.status === 'running') {
                    updateSyncProgress(data.message);
                }
                // For 'pending' status, continue polling
            })
            .catch(error => {
                console.error('Polling error:', error);
                clearInterval(pollInterval);
                displaySyncError('{% trans "Failed to check sync status" %}');
            });
        }, 2000); // Poll every 2 seconds

        // Set a timeout to stop polling after 5 minutes
        setTimeout(() => {
            clearInterval(pollInterval);
            displaySyncError('{% trans "Sync timed out after 5 minutes" %}');
        }, 300000);
    }

    function updateSyncProgress(message) {
        const modalBody = document.getElementById('syncResultsModalBody');
        modalBody.innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <h5>{% trans "Sync in progress..." %}</h5>
                <p class="text-muted">${message}</p>
            </div>
        `;
    }

    function displaySyncError(message) {
        const modalBody = document.getElementById('syncResultsModalBody');
        modalBody.innerHTML = `
            <div class="alert alert-danger text-center">
                <i class="fas fa-exclamation-triangle fa-3x mb-3"></i>
                <h5>{% trans "Sync Failed" %}</h5>
                <p>${message}</p>
            </div>
        `;
    }

    // Helper function to get CSRF token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
</script>
{% endblock %}
