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

{% block content %}
<style>
    .category-box {
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        color: #fff;
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    }
    .lavoro-box { background: linear-gradient(135deg, #4e54c8, #8f94fb); }
    .famiglia-box { background: linear-gradient(135deg, #ff6a00, #ee0979); }
    .personale-box { background: linear-gradient(135deg, #02aab0, #00cdac); }

    .task-column {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        padding: 1.5rem;
        margin-top: 1rem;
        min-height: 300px;
    }
    .task-card {
        background: rgba(255, 255, 255, 0.25);
        border: none;
        border-radius: 10px;
        margin-bottom: 1rem;
        padding: 1rem;
        color: #fff;
        transition: all 0.3s ease;
    }
    .task-card:hover { transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
    .task-card .card-title { font-weight: bold; }
    .task-card .card-text { font-size: 0.9rem; }
    .task-card .datetime { font-size: 0.8rem; opacity: 0.9; }

    .timer-display {
        font-size: 1.5rem;
        font-weight: bold;
        text-align: center;
        margin: 0.5rem 0;
        display: none; /* Initially hidden */
    }
</style>

<div class="container-fluid mt-5">
    <div class="row">
        <!-- Colonna Controlli -->
        <div class="col-lg-3">
            <!-- Assistente -->
            <div class="card bg-light shadow-sm mb-4">
                <div class="card-body text-center">
                    <h5 class="card-title">Roma</h5>
                    <p class="card-text text-muted">Il tuo assistente esecutivo</p>
                    <button class="btn btn-primary" id="btn-assistant">Attiva Assistente</button>
                </div>
            </div>

            <!-- Impostazioni Timer -->
            <div class="card bg-light shadow-sm mb-4">
                <div class="card-body">
                    <h5 class="card-title mb-3">Impostazioni Timer</h5>
                    <div class="mb-3">
                        <label for="work-duration" class="form-label">Durata Lavoro (min)</label>
                        <input type="number" id="work-duration" class="form-control" value="25">
                    </div>
                    <div class="mb-3">
                        <label for="break-duration" class="form-label">Durata Pausa (min)</label>
                        <input type="number" id="break-duration" class="form-control" value="5">
                    </div>
                    <div class="d-grid">
                        <button id="save-timer-settings" class="btn btn-secondary">Salva Impostazioni</button>
                    </div>
                </div>
            </div>

            <!-- Aggiunta Task -->
            <div class="card bg-light shadow-sm">
                <div class="card-body">
                    <h5 class="card-title mb-3">Aggiungi Attività</h5>
                    <form method="post">
                        {% csrf_token %}
                        <div class="mb-3">{{ form.title.label_tag }}{{ form.title }}</div>
                        <div class="mb-3">{{ form.category.label_tag }}{{ form.category }}</div>
                        <div class="row">
                            <div class="col-md-6 mb-3">{{ form.due_date.label_tag }}{{ form.due_date }}</div>
                            <div class="col-md-6 mb-3">{{ form.due_time.label_tag }}{{ form.due_time }}</div>
                        </div>
                        <div class="d-grid"><button type="submit" class="btn btn-success">Aggiungi</button></div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Colonna Categorie Task -->
        <div class="col-lg-9">
            {% for category_value, category_display in categories %}
            <div class="category-box {% if category_value == 'LAVORO' %}lavoro-box{% elif category_value == 'FAMIGLIA' %}famiglia-box{% else %}personale-box{% endif %}">
                <h2 class="mb-3">{{ category_display }}</h2>
                <div class="row">
                    {% for status_id, status_name in statuses %}
                    <div class="col-md-4">
                        <div class="task-column">
                            <h5 class="text-center mb-3">{{ status_name }}</h5>
                            {% for task in tasks|get_item:status_id|get_item:category_value %}
                            <div class="task-card" id="task-{{ task.id }}">
                                <div class="card-body">
                                    <h6 class="card-title">{{ task.title }}</h6>
                                    {% if task.due_date %}<p class="datetime">{{ task.due_date|date:"d M" }}{% if task.due_time %} alle {{ task.due_time|time:"H:i" }}{% endif %}</p>{% endif %}
                                    
                                    <div class="timer-display" id="timer-{{ task.id }}">25:00</div>

                                    <div class="btn-group btn-group-sm mt-2">
                                        {% if status_id != 'COMPLETATO' %}
                                        <button class="btn btn-light start-timer-btn" data-task-id="{{ task.id }}">Avvia Timer</button>
                                        <a href="{% url 'task_edit' task.id %}" class="btn btn-outline-light">Modifica</a>
                                        {% endif %}
                                    </div>

                                    <div class="btn-group btn-group-sm mt-1">
                                        {% if status_id == 'DA_FARE' %}
                                            <a href="{% url 'task_set_status_in_sospeso' task.id %}" class="btn btn-outline-warning">Sospendi</a>
                                            <a href="{% url 'task_set_status_completato' task.id %}" class="btn btn-outline-success">Completa</a>
                                        {% elif status_id == 'IN_SOSPESO' %}
                                            <a href="{% url 'task_set_status_da_fare' task.id %}" class="btn btn-outline-primary">Da Fare</a>
                                            <a href="{% url 'task_set_status_completato' task.id %}" class="btn btn-outline-success">Completa</a>
                                        {% else %}
                                            <a href="{% url 'task_delete' task.id %}" class="btn btn-outline-danger">Elimina</a>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</div>

<!-- Modal Assistente -->
<div class="modal fade" id="assistantModal" tabindex="-1" aria-labelledby="assistantModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="assistantModalLabel">Assistente Roma</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="chat-log" style="height: 400px; overflow-y: auto;">
        <!-- I messaggi della chat verranno inseriti qui -->
      </div>
      <div class="modal-footer">
        <input type="text" id="chat-message-input" class="form-control" placeholder="Scrivi un messaggio...">
        <button id="chat-message-submit" class="btn btn-primary">Invia</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Assistant Chat Logic
    const assistantModal = new bootstrap.Modal(document.getElementById('assistantModal'));
    const btnAssistant = document.getElementById('btn-assistant');
    const chatLog = document.getElementById('chat-log');
    const chatInput = document.getElementById('chat-message-input');
    const chatSubmit = document.getElementById('chat-message-submit');

    btnAssistant.addEventListener('click', () => {
        assistantModal.show();
    });

    const appendMessage = (sender, message) => {
        const messageElement = document.createElement('div');
        messageElement.classList.add('p-2', 'mb-2', 'rounded');
        if (sender === 'user') {
            messageElement.classList.add('bg-primary', 'text-white', 'align-self-end');
            messageElement.style.marginLeft = 'auto';
            messageElement.style.maxWidth = '80%';
        } else {
            messageElement.classList.add('bg-light', 'text-dark');
            messageElement.style.maxWidth = '80%';
        }
        messageElement.textContent = message;
        chatLog.appendChild(messageElement);
        chatLog.scrollTop = chatLog.scrollHeight; // Auto-scroll to bottom
    };

    const handleChatSubmit = () => {
        const message = chatInput.value.trim();
        if (!message) return;

        appendMessage('user', message);
        chatInput.value = '';

        fetch('{% url "assistant_chat" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}', // Required for CSRF protection
            },
            body: JSON.stringify({ message: message })
        })
        .then(response => response.json())
        .then(data => {
            if (data.reply) {
                appendMessage('assistant', data.reply);
            } else if (data.error) {
                appendMessage('assistant', `Error: ${data.error}`);
            }
        })
        .catch(error => {
            console.error('Error during chat fetch:', error);
            appendMessage('assistant', 'Sorry, something went wrong.');
        });
    };

    chatSubmit.addEventListener('click', handleChatSubmit);
    chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            handleChatSubmit();
        }
    });

    // Timer Logic
    let timerInterval = null;
    let activeTimerId = null;
    let isWorkSession = true; // true for work, false for break

    const workDurationInput = document.getElementById('work-duration');
    const breakDurationInput = document.getElementById('break-duration');
    const saveSettingsBtn = document.getElementById('save-timer-settings');

    // Load settings from localStorage
    const loadSettings = () => {
        const savedWorkDuration = localStorage.getItem('pomodoroWorkDuration');
        const savedBreakDuration = localStorage.getItem('pomodoroBreakDuration');
        if (savedWorkDuration) {
            workDurationInput.value = savedWorkDuration;
        }
        if (savedBreakDuration) {
            breakDurationInput.value = savedBreakDuration;
        }
    };

    // Save settings to localStorage
    const saveSettings = () => {
        localStorage.setItem('pomodoroWorkDuration', workDurationInput.value);
        localStorage.setItem('pomodoroBreakDuration', breakDurationInput.value);
        alert('Impostazioni salvate!');
    };

    saveSettingsBtn.addEventListener('click', saveSettings);
    loadSettings(); // Load settings on page startup

    const startTimer = (taskId, durationMinutes) => {
        const timerDisplay = document.getElementById(`timer-${taskId}`);
        const startButton = document.querySelector(`.start-timer-btn[data-task-id="${taskId}"]`);
        
        timerDisplay.style.display = 'block';
        startButton.textContent = 'Ferma Timer';
        activeTimerId = taskId;

        let timeInSeconds = durationMinutes * 60;

        timerInterval = setInterval(() => {
            const minutes = Math.floor(timeInSeconds / 60);
            const seconds = timeInSeconds % 60;
            timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

            if (timeInSeconds <= 0) {
                clearInterval(timerInterval);
                if (isWorkSession) {
                    alert(`Sessione di lavoro completata! Inizia una pausa di ${breakDurationInput.value} minuti.`);
                    isWorkSession = false;
                    startTimer(taskId, parseInt(breakDurationInput.value, 10));
                } else {
                    alert('Pausa terminata! Pronto a tornare al lavoro?');
                    isWorkSession = true;
                    timerDisplay.style.display = 'none';
                    startButton.textContent = 'Avvia Timer';
                    activeTimerId = null;
                }
            } else {
                timeInSeconds--;
            }
        }, 1000);
    };

    document.querySelectorAll('.start-timer-btn').forEach(button => {
        button.addEventListener('click', () => {
            const taskId = button.dataset.taskId;

            // Stop any currently active timer
            if (timerInterval) {
                clearInterval(timerInterval);
                if (activeTimerId) {
                    document.getElementById(`timer-${activeTimerId}`).style.display = 'none';
                    document.querySelector(`.start-timer-btn[data-task-id="${activeTimerId}"]`).textContent = 'Avvia Timer';
                }
            }

            // If clicking the same button that is running, it stops and resets
            if (activeTimerId === taskId) {
                activeTimerId = null;
                isWorkSession = true;
                return;
            }

            // Start a new work session
            isWorkSession = true;
            const workDuration = parseInt(workDurationInput.value, 10);
            startTimer(taskId, workDuration);
        });
    });
});
</script>

{% endblock %}