{% extends 'dashboards/base_dashboard.html' %}

{% block stats %}
<!-- Stats Cards -->
<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-primary shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                        Total Tasks</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ total_tasks }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-success shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                        Completed</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ completed_tasks }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-check-circle fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-warning shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                        In Progress</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ in_progress_tasks }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-sync-alt fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="col-xl-3 col-md-6 mb-4">
    <div class="card border-left-danger shadow h-100 py-2">
        <div class="card-body">
            <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                    <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                        Delayed</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ delayed_tasks }}</div>
                </div>
                <div class="col-auto">
                    <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block left_column %}
<!-- My Tasks -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">My Tasks</h6>
        <div class="dropdown no-arrow">
            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
                <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
            </a>
            <ul class="dropdown-menu dropdown-menu-end shadow" aria-labelledby="dropdownMenuLink">
                <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#addCommentModal"><i class="fas fa-comment me-2"></i>Add Comment</a></li>
                <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#uploadFileModal"><i class="fas fa-upload me-2"></i>Upload File</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item" href="#"><i class="fas fa-sync-alt me-2"></i>Refresh</a></li>
            </ul>
        </div>
    </div>
    <div class="card-body">
        {% if recent_tasks %}
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Status</th>
                            <th>Due Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for task in recent_tasks %}
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    {% if task.attachments.exists %}
                                    <i class="fas fa-paperclip me-2 text-muted"></i>
                                    {% endif %}
                                    <div>
                                        <h6 class="mb-0">{{ task.title|truncatechars:30 }}</h6>
                                        <small class="text-muted">Created by {{ task.created_by.get_full_name|default:task.created_by.username }}</small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge {% if task.status == 'completed' %}bg-success
                                {% elif task.status == 'in_progress' %}bg-info
                                {% elif task.due_date < time_now and task.status != 'completed' %}bg-danger
                                {% else %}bg-warning{% endif %}">
                                    {{ task.get_status_display }}
                                </span>
                            </td>
                            <td>{{ task.due_date|date:"M d, Y" }}</td>
                            <td>
                                <div class="btn-group" role="group">
                                    <a href="{% url 'tasks:task-detail' task.id %}" class="btn btn-sm btn-outline-primary" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="fas fa-cog"></i>
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item task-action" href="#" data-task-id="{{ task.id }}" data-action="start"><i class="fas fa-play me-2"></i>Start</a></li>
                                        <li><a class="dropdown-item task-action" href="#" data-task-id="{{ task.id }}" data-action="complete"><i class="fas fa-check me-2"></i>Complete</a></li>
                                        <li><a class="dropdown-item task-action" href="#" data-task-id="{{ task.id }}" data-action="delay"><i class="fas fa-clock me-2"></i>Delay</a></li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#addCommentModal" data-task-id="{{ task.id }}"><i class="fas fa-comment me-2"></i>Add Comment</a></li>
                                        <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#uploadFileModal" data-task-id="{{ task.id }}"><i class="fas fa-upload me-2"></i>Upload File</a></li>
                                    </ul>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            <div class="mt-3 text-center">
                <a href="{% url 'tasks:task-list' %}" class="btn btn-outline-primary btn-sm">View All Tasks</a>
            </div>
        {% else %}
            <div class="text-center py-4">
                <i class="fas fa-tasks fa-3x text-gray-300 mb-3"></i>
                <p class="text-muted">You don't have any tasks assigned yet.</p>
            </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block right_column %}
<!-- Quick Actions -->
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Quick Actions</h6>
    </div>
    <div class="card-body">
        <div class="d-grid gap-2">
            <button type="button" class="btn btn-outline-primary btn-sm mb-2 quick-action" data-action="upload">
                <i class="fas fa-upload me-1"></i> Upload Document
            </button>
            <button type="button" class="btn btn-outline-primary btn-sm mb-2 quick-action" data-action="meeting">
                <i class="fas fa-calendar-plus me-1"></i> Schedule Meeting
            </button>
            <button type="button" class="btn btn-outline-primary btn-sm quick-action" data-action="report">
                <i class="fas fa-envelope me-1"></i> Send Report
            </button>
        </div>
    </div>
</div>

<!-- Task Status -->
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Task Status</h6>
    </div>
    <div class="card-body">
        <div class="mb-3">
            <div class="d-flex justify-content-between mb-1">
                <span>Completed</span>
                <span>{{ completed_tasks }} of {{ total_tasks }}</span>
            </div>
            <div class="progress">
                <div class="progress-bar bg-success" role="progressbar" 
                     style="width: {% if total_tasks > 0 %}{% widthratio completed_tasks total_tasks 100 %}{% else %}0{% endif %}%" 
                     aria-valuenow="{{ completed_tasks }}" aria-valuemin="0" aria-valuemax="{{ total_tasks }}">
                </div>
            </div>
        </div>
        <div class="mt-4">
            <h6 class="font-weight-bold">Upcoming Deadlines</h6>
            <ul class="list-group list-group-flush">
                {% for task in recent_tasks|slice:":3" %}
                <li class="list-group-item d-flex justify-content-between align-items-center px-0">
                    <div>
                        <h6 class="mb-0 small">{{ task.title|truncatechars:30 }}</h6>
                        <small class="text-muted">Due: {{ task.due_date|date:"M d, Y" }}</small>
                    </div>
                    <span class="badge {% if task.status == 'completed' %}bg-success{% else %}bg-warning{% endif %} rounded-pill">
                        {{ task.get_status_display }}
                    </span>
                </li>
                {% empty %}
                <li class="list-group-item">No upcoming deadlines</li>
                {% endfor %}
            </ul>
        </div>
    </div>
</div>
{% endblock %}

<!-- Add Comment Modal -->
<div class="modal fade" id="addCommentModal" tabindex="-1" aria-labelledby="addCommentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addCommentModalLabel">Add Comment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="commentForm" method="post" action="{% url 'tasks:add-comment' %}">
                {% csrf_token %}
                <input type="hidden" name="task_id" id="commentTaskId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="commentText" class="form-label">Your Comment</label>
                        <textarea class="form-control" id="commentText" name="comment" rows="4" required></textarea>
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="notifyUsers" name="notify_users" checked>
                        <label class="form-check-label" for="notifyUsers">
                            Notify task participants
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Post Comment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Upload File Modal -->
<div class="modal fade" id="uploadFileModal" tabindex="-1" aria-labelledby="uploadFileModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="uploadFileModalLabel">Upload File</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="fileUploadForm" method="post" enctype="multipart/form-data" action="{% url 'tasks:upload-attachment' %}">
                {% csrf_token %}
                <input type="hidden" name="task_id" id="uploadTaskId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="fileInput" class="form-label">Choose file</label>
                        <input class="form-control" type="file" id="fileInput" name="file" required>
                    </div>
                    <div class="mb-3">
                        <label for="fileDescription" class="form-label">Description (optional)</label>
                        <input type="text" class="form-control" id="fileDescription" name="description" placeholder="Brief description of the file">
                    </div>
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="notifyFileUpload" name="notify_users" checked>
                        <label class="form-check-label" for="notifyFileUpload">
                            Notify task participants
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>

{% block extra_js %}
<script>
// Toast notification function
function showToast(title, message, type = 'info') {
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    const toastId = 'toast-' + Date.now();
    const toast = document.createElement('div');
    toast.id = toastId;
    toast.className = 'toast align-items-center text-white bg-' + getToastClass(type) + ' border-0';
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                <strong>${title}</strong><br>${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast, { autohide: true, delay: 5000 });
    bsToast.show();
    
    // Remove toast from DOM after it's hidden
    toast.addEventListener('hidden.bs.toast', function () {
        toast.remove();
    });
}

function getToastClass(type) {
    const classes = {
        'success': 'success',
        'error': 'danger',
        'warning': 'warning',
        'info': 'info'
    };
    return classes[type] || 'info';
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
    container.style.zIndex = '11';
    document.body.appendChild(container);
    return container;
}

document.addEventListener('DOMContentLoaded', function() {
    // Handle task status updates
    document.querySelectorAll('.task-action').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const taskId = this.dataset.taskId;
            const action = this.dataset.action;
            const taskRow = this.closest('tr');
            
            // Show loading state
            const originalText = this.innerHTML;
            this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
            this.disabled = true;
            
            // Map action to status
            const statusMap = {
                'start': 'in_progress',
                'complete': 'completed',
                'delay': 'delayed'
            };
            
            const status = statusMap[action];
            if (!status) {
                showToast('Error', 'Invalid action', 'error');
                return;
            }
            
            // Send request to update task status
            fetch(`/tasks/api/tasks/${taskId}/status/`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ status: status }),
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.error || 'Failed to update task status');
                    });
                }
                return response.json();
            })
            .then(data => {
                showToast('Success', `Task marked as ${status.replace('_', ' ')}`, 'success');
                // Update the status badge
                const statusBadge = taskRow.querySelector('.task-status');
                if (statusBadge) {
                    statusBadge.textContent = data.status_display || status;
                    // Update badge class based on status
                    statusBadge.className = 'badge ' + getStatusBadgeClass(status);
                }
                // Reload the page to reflect all changes
                setTimeout(() => window.location.reload(), 1000);
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('Error', error.message || 'An error occurred while updating the task', 'error');
                this.innerHTML = originalText;
                this.disabled = false;
            });
        });
    });
    
    // Helper function to get badge class based on status
    function getStatusBadgeClass(status) {
        const statusClasses = {
            'completed': 'bg-success',
            'in_progress': 'bg-info',
            'delayed': 'bg-warning',
            'pending': 'bg-secondary'
        };
        return statusClasses[status] || 'bg-secondary';
    }

    // Handle comment modal
    const commentModal = document.getElementById('addCommentModal');
    if (commentModal) {
        commentModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const taskId = button.getAttribute('data-task-id');
            const taskTitle = button.closest('tr').querySelector('h6').textContent;
            const modalTitle = commentModal.querySelector('.modal-title');
            const taskIdInput = commentModal.querySelector('input[name="task_id"]');
            const commentForm = commentModal.querySelector('form');
            
            modalTitle.textContent = `Add Comment - ${taskTitle}`;
            taskIdInput.value = taskId;
            
            // Reset form
            if (commentForm) {
                commentForm.reset();
            }
        });
    }

    // Handle Quick Actions buttons
    document.querySelectorAll('.quick-action').forEach(button => {
        button.addEventListener('click', function() {
            const action = this.dataset.action;
            const buttonText = this.textContent.trim();
            const originalHTML = this.innerHTML;
            
            // Show loading state
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
            
            // Simulate API call with a timeout
            setTimeout(() => {
                switch(action) {
                    case 'upload':
                        // Trigger the file upload modal
                        const uploadBtn = document.querySelector('[data-bs-target="#uploadFileModal"]');
                        if (uploadBtn) {
                            uploadBtn.click();
                        } else {
                            showToast('Info', 'File upload functionality will open a file dialog', 'info');
                        }
                        break;
                        
                    case 'meeting':
                        // Open meeting scheduling (placeholder for now)
                        showToast('Coming Soon', 'Meeting scheduling feature will be available soon!', 'info');
                        break;
                        
                    case 'report':
                        // Open report sending (placeholder for now)
                        showToast('Coming Soon', 'Report sending feature will be available soon!', 'info');
                        break;
                }
                
                // Reset button state after a short delay
                setTimeout(() => {
                    this.disabled = false;
                    this.innerHTML = originalHTML;
                }, 1000);
                
            }, 500);
        });
    });

    // Handle file upload modal
    const fileModal = document.getElementById('uploadFileModal');
    if (fileModal) {
        fileModal.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const taskId = button.getAttribute('data-task-id');
            const taskTitle = button.closest('tr').querySelector('h6').textContent;
            const modalTitle = fileModal.querySelector('.modal-title');
            const taskIdInput = fileModal.querySelector('input[name="task_id"]');
            const fileForm = fileModal.querySelector('form');
            
            modalTitle.textContent = `Upload File - ${taskTitle}`;
            taskIdInput.value = taskId;
            
            // Reset form
            if (fileForm) {
                fileForm.reset();
                // Reset file input label
                const fileInput = fileForm.querySelector('input[type="file"]');
                const fileLabel = fileForm.querySelector('.custom-file-label');
                if (fileLabel) {
                    fileLabel.textContent = 'Choose file';
                }
            }
        });
    }
    
    // Update file input label when a file is selected
    document.querySelectorAll('.custom-file-input').forEach(input => {
        input.addEventListener('change', function() {
            const fileName = this.files[0] ? this.files[0].name : 'Choose file';
            const label = this.nextElementSibling;
            if (label && label.classList.contains('custom-file-label')) {
                label.textContent = fileName;
            }
        });
    });

    // Form submission handling with fetch
    const commentForm = document.getElementById('commentForm');
    if (commentForm) {
        commentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;
            
            // Show loading state
            submitButton.disabled = true;
            submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Adding...';
            
            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || 'Failed to add comment');
                    });
                }
                return response.json();
            })
            .then(data => {
                // Close the modal
                const modal = bootstrap.Modal.getInstance(commentModal);
                if (modal) {
                    modal.hide();
                }
                
                // Show success message
                showToast('Success', 'Comment added successfully', 'success');
                
                // Reload the page to show the new comment
                setTimeout(() => window.location.reload(), 1000);
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('Error', error.message || 'Failed to add comment', 'error');
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            });
            
            return false;
        });
    }
    
    // Handle file upload form
    const fileUploadForm = document.getElementById('fileUploadForm');
    if (fileUploadForm) {
        fileUploadForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;
            
            // Validate file size (max 10MB)
            const fileInput = this.querySelector('input[type="file"]');
            if (fileInput.files.length > 0) {
                const fileSize = fileInput.files[0].size / 1024 / 1024; // Convert to MB
                if (fileSize > 10) {
                    showToast('Error', 'File size must be less than 10MB', 'error');
                    return false;
                }
            } else {
                showToast('Error', 'Please select a file to upload', 'error');
                return false;
            }
            
            // Show loading state
            submitButton.disabled = true;
            submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Uploading...';
            
            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || 'Failed to upload file');
                    });
                }
                return response.json();
            })
            .then(data => {
                // Close the modal
                const modal = bootstrap.Modal.getInstance(fileModal);
                if (modal) {
                    modal.hide();
                }
                
                // Show success message
                showToast('Success', 'File uploaded successfully', 'success');
                
                // Reload the page to show the new file
                setTimeout(() => window.location.reload(), 1000);
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('Error', error.message || 'Failed to upload file', 'error');
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            });
            
            return false;
        });
        toast.setAttribute('aria-live', 'assertive');
        toast.setAttribute('aria-atomic', 'true');
        
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">
                    <strong>${title}</strong><br>${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        `;
        
        toastContainer.appendChild(toast);
        const bsToast = new bootstrap.Toast(toast, { autohide: true, delay: 5000 });
        bsToast.show();
        
        // Remove toast from DOM after it's hidden
        toast.addEventListener('hidden.bs.toast', function () {
            toast.remove();
        });
    }
    
    function getToastClass(type) {
        const classes = {
            'success': 'success',
            'error': 'danger',
            'warning': 'warning',
            'info': 'info'
        };
        return classes[type] || 'info';
    }
    
    function createToastContainer() {
        const container = document.createElement('div');
        container.id = 'toastContainer';
        container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        container.style.zIndex = '11';
        document.body.appendChild(container);
        return container;
    }
});
</script>
{% endblock %}
