{% extends 'backoffice/base.html' %}
{% load static %}

{% block title %}{{ page_title }} - ECOLUX Dashboard{% endblock %}

{% block content %}
<section class="section is-main-section">
    <div class="level">
        <div class="level-left">
            <div class="level-item">
                <div class="title">
                    <h1 class="title is-3 has-text-ecolux-primary">
                        <span class="icon-text">
                            <span class="icon has-text-ecolux-secondary">
                                <i class="fas fa-project-diagram"></i>
                            </span>
                            <span>{{ page_title }}</span>
                        </span>
                    </h1>
                </div>
            </div>
        </div>
        <div class="level-right">
            <div class="level-item">
                <div class="buttons">
                    <a href="{% url 'app:dashboard_home' %}" class="button is-light">
                        <span class="icon">
                            <i class="fas fa-arrow-left"></i>
                        </span>
                        <span>Retour au tableau de bord</span>
                    </a>
                    {% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
                    <button class="button is-ecolux-primary" onclick="openCreateProjectModal()">
                        <span class="icon">
                            <i class="fas fa-plus"></i>
                        </span>
                        <span>Nouveau Projet</span>
                    </button>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Filtres -->
    <div class="card ecolux-card mb-5">
        <div class="card-content">
            <form method="GET" class="field is-grouped">
                <div class="control">
                    <div class="field has-addons">
                        <div class="control">
                            <span class="button is-static ecolux-primary">
                                <i class="fas fa-filter"></i>
                            </span>
                        </div>
                        <div class="control">
                            <div class="select">
                                <select name="status" onchange="this.form.submit()">
                                    <option value="">Tous les statuts</option>
                                    {% for value, label in status_choices %}
                                        <option value="{{ value }}" {% if current_status == value %}selected{% endif %}>
                                            {{ label }}
                                        </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="control is-expanded">
                    <input class="input" type="text" name="search" placeholder="Rechercher un projet..." 
                           value="{{ search_query }}">
                </div>
                <div class="control">
                    <button type="submit" class="button is-ecolux-primary">
                        <span class="icon">
                            <i class="fas fa-search"></i>
                        </span>
                    </button>
                </div>
                {% if current_status or search_query %}
                <div class="control">
                    <a href="{% url 'app:dashboard_projects_list' %}" class="button is-light">
                        <span class="icon">
                            <i class="fas fa-times"></i>
                        </span>
                        <span>Effacer</span>
                    </a>
                </div>
                {% endif %}
            </form>
        </div>
    </div>

    <!-- Liste des projets -->
    <div class="card ecolux-card">
        <header class="card-header ecolux-primary">
            <p class="card-header-title has-text-ecolux-secondary">
                <span class="icon">
                    <i class="fas fa-list"></i>
                </span>
                Liste des projets
            </p>
        </header>
        <div class="card-content">
            {% if page_obj %}
                {% for project in page_obj %}
                <div class="media" style="border-bottom: 1px solid #f1f3f4; padding-bottom: 1rem; margin-bottom: 1rem;">
                    <div class="media-content">
                        <div class="content">
                            <p>
                                <strong>
                                    <a href="{% url 'app:dashboard_project_detail' project.id %}" class="ecolux-link">
                                        {{ project.title }}
                                    </a>
                                </strong>
                                {% if project.status == 'PLANNING' %}
                                    <span class="tag is-ecolux-secondary is-small">{{ project.get_status_display }}</span>
                                {% elif project.status == 'IN_PROGRESS' %}
                                    <span class="tag is-ecolux-primary is-small">{{ project.get_status_display }}</span>
                                {% elif project.status == 'COMPLETED' %}
                                    <span class="tag is-success is-small">{{ project.get_status_display }}</span>
                                {% elif project.status == 'PAUSED' %}
                                    <span class="tag is-warning is-small">{{ project.get_status_display }}</span>
                                {% else %}
                                    <span class="tag is-light is-small">{{ project.get_status_display }}</span>
                                {% endif %}
                                <br>
                                {{ project.description|striptags|truncatewords:20 }}
                                <br>
                                <small>
                                    <strong class="has-text-ecolux-primary">Client:</strong> {{ project.client.user.get_full_name }}
                                    {% if project.budget %}
                                        &nbsp;|&nbsp;
                                        <strong class="has-text-ecolux-primary">Budget:</strong> {{ project.budget|floatformat:0 }} FCFA
                                    {% endif %}
                                </small>
                                <br>
                                <small class="has-text-grey">
                                    Créé le {{ project.created_at|date:"d/m/Y à H:i" }}
                                    {% if project.start_date %}
                                        - Début: {{ project.start_date|date:"d/m/Y" }}
                                    {% endif %}
                                    {% if project.end_date %}
                                        - Fin prévue: {{ project.end_date|date:"d/m/Y" }}
                                    {% endif %}
                                </small>
                            </p>
                            
                            <!-- Actions pour DRH et TECHNICIEN -->
                            {% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
                            <div class="buttons are-small">
                                <button class="button is-ecolux-secondary is-light" onclick="editProject({{ project.id }})">
                                    <span class="icon">
                                        <i class="fas fa-edit"></i>
                                    </span>
                                    <span>Modifier</span>
                                </button>
                                <button class="button is-ecolux-primary is-light" onclick="assignTechnician({{ project.id }})">
                                    <span class="icon">
                                        <i class="fas fa-user-plus"></i>
                                    </span>
                                    <span>Affecter</span>
                                </button>
                                {% if user_type == 'DRH' %}
                                <button class="button is-danger is-light" onclick="deleteProject({{ project.id }})">
                                    <span class="icon">
                                        <i class="fas fa-trash"></i>
                                    </span>
                                </button>
                                {% endif %}
                            </div>
                            {% endif %}
                            
                            <!-- Techniciens assignés -->
                            {% if project.assigned_technicians.count > 0 %}
                            <div class="tags">
                                <span class="tag is-light">Techniciens:</span>
                                {% for tech in project.assigned_technicians.all %}
                                    <span class="tag is-ecolux-primary">
                                        {{ tech.user.get_full_name|default:tech.user.username }}
                                    </span>
                                {% endfor %}
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div class="notification is-ecolux-primary is-light">
                    <div class="content has-text-centered">
                        <p>
                            <span class="icon is-large">
                                <i class="fas fa-info-circle fa-2x"></i>
                            </span>
                        </p>
                        <p class="title is-5">Aucun projet trouvé</p>
                        <p>
                            {% if current_status or search_query %}
                                Aucun projet ne correspond à vos critères de recherche.
                                <br>
                                <a href="{% url 'app:dashboard_projects_list' %}" class="button is-light mt-3">
                                    Voir tous les projets
                                </a>
                            {% else %}
                                Commencez par créer votre premier projet.
                                {% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
                                <br>
                                <button class="button is-ecolux-primary mt-3" onclick="openCreateProjectModal()">
                                    <span class="icon">
                                        <i class="fas fa-plus"></i>
                                    </span>
                                    <span>Créer un projet</span>
                                </button>
                                {% endif %}
                            {% endif %}
                        </p>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>

    <!-- Pagination -->
    {% if page_obj.has_other_pages %}
    <nav class="pagination is-centered mt-5" role="navigation" aria-label="pagination">
        {% if page_obj.has_previous %}
            <a class="pagination-previous button is-ecolux-primary" href="?page={{ page_obj.previous_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}">
                <span class="icon">
                    <i class="fas fa-chevron-left"></i>
                </span>
                <span>Précédent</span>
            </a>
        {% endif %}
        
        {% if page_obj.has_next %}
            <a class="pagination-next button is-ecolux-primary" href="?page={{ page_obj.next_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}">
                <span>Suivant</span>
                <span class="icon">
                    <i class="fas fa-chevron-right"></i>
                </span>
            </a>
        {% endif %}
        
        <ul class="pagination-list">
            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    <li><a class="pagination-link is-current ecolux-primary">{{ num }}</a></li>
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <li><a class="pagination-link" href="?page={{ num }}{% if current_status %}&status={{ current_status }}{% endif %}{% if search_query %}&search={{ search_query }}{% endif %}">{{ num }}</a></li>
                {% endif %}
            {% endfor %}
        </ul>
    </nav>
    {% endif %}
</section>

<!-- Modal pour créer un projet -->
{% if user_type == 'DRH' or user_type == 'TECHNICIEN' %}
<div class="modal" id="createProjectModal">
    <div class="modal-background" onclick="closeCreateProjectModal()"></div>
    <div class="modal-card ecolux-card">
        <header class="modal-card-head ecolux-primary">
            <p class="modal-card-title has-text-ecolux-secondary">
                <span class="icon-text">
                    <span class="icon">
                        <i class="fas fa-plus-circle"></i>
                    </span>
                    <span>Nouveau Projet</span>
                </span>
            </p>
            <button class="delete" aria-label="close" onclick="closeCreateProjectModal()"></button>
        </header>
        <section class="modal-card-body">
            <form id="createProjectForm">
                <div class="field">
                    <label class="label has-text-ecolux-primary">Titre du projet</label>
                    <div class="control has-icons-left">
                        <input class="input" type="text" name="title" placeholder="Nom du projet" required>
                        <span class="icon is-small is-left">
                            <i class="fas fa-tag"></i>
                        </span>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Description</label>
                    <div class="control">
                        <textarea class="textarea" name="description" placeholder="Description du projet" rows="4" required></textarea>
                    </div>
                </div>

                <div class="field">
                    <label class="label has-text-ecolux-primary">Client</label>
                    <div class="control has-icons-left">
                        <div class="select is-fullwidth">
                            <select name="client_id" required>
                                <option value="">Sélectionner un client</option>
                            </select>
                        </div>
                        <span class="icon is-small is-left">
                            <i class="fas fa-user"></i>
                        </span>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Budget (FCFA)</label>
                            <div class="control has-icons-left">
                                <input class="input" type="number" name="budget" placeholder="Budget estimé">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-coins"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Statut</label>
                            <div class="control has-icons-left">
                                <div class="select is-fullwidth">
                                    <select name="status">
                                        <option value="PLANNING">Planification</option>
                                        <option value="IN_PROGRESS">En cours</option>
                                        <option value="PAUSED">En pause</option>
                                        <option value="COMPLETED">Terminé</option>
                                        <option value="CANCELLED">Annulé</option>
                                    </select>
                                </div>
                                <span class="icon is-small is-left">
                                    <i class="fas fa-tasks"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="columns">
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date de début</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" name="start_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-alt"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="field">
                            <label class="label has-text-ecolux-primary">Date de fin prévue</label>
                            <div class="control has-icons-left">
                                <input class="input" type="date" name="end_date">
                                <span class="icon is-small is-left">
                                    <i class="fas fa-calendar-check"></i>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </section>
        <footer class="modal-card-foot">
            <button class="button is-ecolux-primary" onclick="submitCreateProject()">
                <span class="icon">
                    <i class="fas fa-save"></i>
                </span>
                <span>Créer le projet</span>
            </button>
            <button class="button" onclick="closeCreateProjectModal()">Annuler</button>
        </footer>
    </div>
</div>
{% endif %}

<script>
// Variables globales
let clients = [];

// Charger les clients au chargement de la page
document.addEventListener('DOMContentLoaded', function() {
    loadClients();
});

// Fonctions pour le modal de création de projet
function openCreateProjectModal() {
    document.getElementById('createProjectModal').classList.add('is-active');
    document.getElementById('createProjectForm').reset();
    loadClients();
}

function closeCreateProjectModal() {
    document.getElementById('createProjectModal').classList.remove('is-active');
}

function loadClients() {
    fetch('{% url "app:get_clients_list" %}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                clients = data.clients;
                const clientSelect = document.querySelector('select[name="client_id"]');
                clientSelect.innerHTML = '<option value="">Sélectionner un client</option>';
                
                clients.forEach(client => {
                    const option = document.createElement('option');
                    option.value = client.id;
                    option.textContent = `${client.name} (${client.email})`;
                    clientSelect.appendChild(option);
                });
            }
        })
        .catch(error => {
            console.error('Erreur lors du chargement des clients:', error);
            showNotification('Erreur lors du chargement des clients', 'is-danger');
        });
}

function submitCreateProject() {
    const form = document.getElementById('createProjectForm');
    const formData = new FormData(form);
    
    const projectData = {
        title: formData.get('title'),
        description: formData.get('description'),
        client_id: formData.get('client_id'),
        budget: formData.get('budget') || null,
        status: formData.get('status'),
        start_date: formData.get('start_date') || null,
        end_date: formData.get('end_date') || null,
    };
    
    // Validation
    if (!projectData.title || !projectData.description || !projectData.client_id) {
        showNotification('Veuillez remplir tous les champs obligatoires', 'is-warning');
        return;
    }
    
    fetch('{% url "app:create_dashboard_project" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: JSON.stringify(projectData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'is-success');
            closeCreateProjectModal();
            // Recharger la page pour voir le nouveau projet
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showNotification(data.error || 'Erreur lors de la création du projet', 'is-danger');
        }
    })
    .catch(error => {
        console.error('Erreur:', error);
        showNotification('Erreur lors de la création du projet', 'is-danger');
    });
}

// Fonctions pour les actions sur les projets
function editProject(projectId) {
    showNotification('Fonction d\'édition en cours de développement', 'is-info');
}

function assignTechnician(projectId) {
    showNotification('Fonction d\'affectation en cours de développement', 'is-info');
}

function deleteProject(projectId) {
    if (confirm('Êtes-vous sûr de vouloir supprimer ce projet ?')) {
        showNotification('Fonction de suppression en cours de développement', 'is-info');
    }
}

// Fonction pour afficher les notifications
function showNotification(message, type) {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        <button class="delete" onclick="this.parentElement.remove()"></button>
        ${message}
    `;
    
    document.body.appendChild(notification);
    
    // Supprimer automatiquement après 5 secondes
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}
</script>

{% csrf_token %}
{% endblock %}
