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

{% block title %}{{ user_role|title }} Dashboard{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">{{ user_role|title }} Dashboard</h1>
        <div class="d-flex
            <span class="badge bg-primary text-white p-2 me-2">
                {{ user.get_full_name|default:user.email }}
            </span>
            <span class="badge bg-success text-white p-2">
                {{ user_role|title }}
                {% if user.department %}
                    - {{ user.department.name }}
                {% endif %}
            </span>
        </div>
    </div>

    <!-- Stats Row -->
    <div class="row">
        {% block stats %}{% endblock %}
    </div>

    <!-- Main Content -->
    <div class="row">
        <!-- Left Column -->
        <div class="col-lg-8">
            {% block left_column %}{% endblock %}
        </div>

        <!-- Right Column -->
        <div class="col-lg-4">
            {% block right_column %}{% endblock %}
        </div>
    </div>
</div>

<!-- Modals -->
<!-- Create Task Modal -->
<div class="modal fade" id="createTaskModal" tabindex="-1" aria-labelledby="createTaskModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="createTaskModalLabel">Create New Task</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="{% url 'tasks:task-create' %}">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="taskTitle" class="form-label">Task Title</label>
                        <input type="text" class="form-control" id="taskTitle" name="title" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="assignedTo" class="form-label">Assign To</label>
                                <select class="form-select" id="assignedTo" name="assigned_to" required>
                                    <option value="">Select Team Member</option>
                                    {% for member in request.user.section.user_set.all %}
                                    <option value="{{ member.id }}">{{ member.get_full_name|default:member.email }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="dueDate" class="form-label">Due Date</label>
                                <input type="date" class="form-control" id="dueDate" name="due_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="taskDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="taskDescription" name="description" rows="4"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="taskPriority" class="form-label">Priority</label>
                                <select class="form-select" id="taskPriority" name="priority">
                                    <option value="low">Low</option>
                                    <option value="medium" selected>Medium</option>
                                    <option value="high">High</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="taskStatus" class="form-label">Status</label>
                                <select class="form-select" id="taskStatus" name="status">
                                    <option value="pending">Pending</option>
                                    <option value="in_progress">In Progress</option>
                                    <option value="completed">Completed</option>
                                </select>
                            </div>
                        </div>
                    </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">Create Task</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Assign Task Modal -->
<div class="modal fade" id="assignTaskModal" tabindex="-1" aria-labelledby="assignTaskModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="assignTaskModalLabel">Assign Task</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="{% url 'tasks:task-assign' %}" id="assignTaskForm">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="taskSelect" class="form-label">Select Task</label>
                        <select class="form-select" id="taskSelect" name="task_id" required>
                            <option value="">Choose a task...</option>
                            {% if recent_tasks %}
                                {% for task in recent_tasks %}
                                <option value="{{ task.id }}">{{ task.title }} ({{ task.get_status_display }})</option>
                                {% endfor %}
                            {% endif %}
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="assignTo" class="form-label">Assign To</label>
                        <select class="form-select" id="assignTo" name="assigned_to" required>
                            <option value="">Select Team Member</option>
                            {% for member in team_members %}
                            <option value="{{ member.id }}">{{ member.get_full_name|default:member.email }}</option>
                            {% endfor %}
                        </select>
                    </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">Assign Task</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Submit Report Modal -->
<div class="modal fade" id="submitReportModal" tabindex="-1" aria-labelledby="submitReportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="submitReportModalLabel">Submit Report to Director General</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="reportForm" method="post" enctype="multipart/form-data" action="{% url 'reports:submit' %}">
                {% csrf_token %}
                <div class="modal-body">
                    <div id="formAlerts"></div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="reportTitle" class="form-label">Report Title</label>
                            <input type="text" class="form-control" id="reportTitle" name="title" required>
                            <div class="invalid-feedback">Please provide a title for the report.</div>
                        </div>
                        <div class="col-md-6">
                            <label for="reportType" class="form-label">Report Type</label>
                            <select class="form-select" id="reportType" name="report_type" required>
                                <option value="">Select Report Type</option>
                                <option value="weekly">Weekly Report</option>
                                <option value="monthly" selected>Monthly Report</option>
                                <option value="quarterly">Quarterly Report</option>
                                <option value="annual">Annual Report</option>
                                <option value="ad_hoc">Ad Hoc Report</option>
                            </select>
                            <div class="invalid-feedback">Please select a report type.</div>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="periodStart" class="form-label">Period Start</label>
                            <input type="date" class="form-control" id="periodStart" name="period_start" required>
                            <div class="invalid-feedback">Please provide a start date.</div>
                        </div>
                        <div class="col-md-6">
                            <label for="periodEnd" class="form-label">Period End</label>
                            <input type="date" class="form-control" id="periodEnd" name="period_end" required>
                            <div class="invalid-feedback">Please provide an end date.</div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="reportFile" class="form-label">Attach File (Optional)</label>
                        <input class="form-control" type="file" id="reportFile" name="file" accept=".pdf,.doc,.docx,.xls,.xlsx,.csv">
                        <div class="form-text">Accepted formats: PDF, Word, Excel, CSV (Max 10MB)</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="reportContent" class="form-label">Report Content</label>
                        <textarea class="form-control" id="reportContent" name="content" rows="6" required></textarea>
                        <div class="invalid-feedback">Please provide the report content.</div>
                        <div class="form-text">You can format your report using Markdown syntax.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-success" id="submitReportBtn">
                        <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                        <i class="bi bi-send"></i> Submit Report
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Generate Report Modal -->
<div class="modal fade" id="generateReportModal" tabindex="-1" aria-labelledby="generateReportModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="generateReportModalLabel">Generate Section Report</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="get" action="{% url 'reports:generate' %}">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="reportType" class="form-label">Report Type</label>
                        <select class="form-select" id="reportType" name="type" required>
                            <option value="tasks">Tasks Overview</option>
                            <option value="performance">Team Performance</option>
                            <option value="completion">Task Completion</option>
                            <option value="delays">Delayed Tasks</option>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="startDate" class="form-label">Start Date</label>
                                <input type="date" class="form-control" id="startDate" name="start_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="endDate" class="form-label">End Date</label>
                                <input type="date" class="form-control" id="endDate" name="end_date" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="format" class="form-label">Format</label>
                        <select class="form-select" id="format" name="format">
                            <option value="pdf">PDF</option>
                            <option value="excel">Excel</option>
                            <option value="csv">CSV</option>
                        </select>
                    </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">
                        <i class="fas fa-download me-1"></i> Generate Report
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Initialize Date Pickers -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Set default dates for reports
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    
    // Format dates as YYYY-MM-DD
    const formatDate = (date) => {
        const d = new Date(date);
        let month = '' + (d.getMonth() + 1);
        let day = '' + d.getDate();
        const year = d.getFullYear();

        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;

        return [year, month, day].join('-');
    };

    // Set default dates
    document.getElementById('startDate').value = formatDate(firstDay);
    document.getElementById('endDate').value = formatDate(today);
    
    // Initialize date pickers
    flatpickr("input[type='datetime-local']", {
        enableTime: true,
        dateFormat: "Y-m-d H:i",
        time_24hr: true
    });
    
    // Handle task assignment form submission
    const assignTaskForm = document.getElementById('assignTaskForm');
    if (assignTaskForm) {
        assignTaskForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitButton = this.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;
            
            // Disable submit button and show loading state
            submitButton.disabled = true;
            submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Assigning...';
            
            // Get CSRF token
            const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
            
            // Submit form via AJAX
            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': csrftoken
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    const successAlert = `
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            ${data.message}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    
                    // Insert alert before the form
                    this.insertAdjacentHTML('beforebegin', successAlert);
                    
                    // Close the modal after a short delay
                    const modal = bootstrap.Modal.getInstance(document.getElementById('assignTaskModal'));
                    setTimeout(() => {
                        modal.hide();
                        // Reload the page to show updated task list
                        window.location.reload();
                    }, 1500);
                } else {
                    // Show error message
                    const errorAlert = `
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            ${data.message || 'An error occurred while assigning the task.'}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    
                    // Insert alert before the form
                    this.insertAdjacentHTML('beforebegin', errorAlert);
                    
                    // Re-enable submit button
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalButtonText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                
                // Show error message
                const errorAlert = `
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        An unexpected error occurred. Please try again.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                `;
                
                // Insert alert before the form
                this.insertAdjacentHTML('beforebegin', errorAlert);
                
                // Re-enable submit button
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            });
        });
    }
    
    // Set task due date to tomorrow
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    document.getElementById('dueDate').value = formatDate(tomorrow);
    
    // Handle report form submission
    const reportForm = document.getElementById('reportForm');
    if (reportForm) {
        reportForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(reportForm);
            const submitBtn = reportForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            
            // Show loading state
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Submitting...';
            
            // Clear previous alerts
            const formAlerts = document.getElementById('formAlerts');
            formAlerts.innerHTML = '';
            
            // Submit form via AJAX
            fetch(reportForm.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': '{{ csrf_token }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    const alert = `
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="bi bi-check-circle me-2"></i>
                            ${data.message}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    formAlerts.insertAdjacentHTML('afterbegin', alert);
                    
                    // Reset form
                    reportForm.reset();
                    
                    // Close modal after delay
                    setTimeout(() => {
                        const modal = bootstrap.Modal.getInstance(document.getElementById('submitReportModal'));
                        if (modal) {
                            modal.hide();
                        }
                        // Show success toast
                        showToast('Success', data.message, 'success');
                        
                        // Reload the page to update the reports list
                        setTimeout(() => window.location.reload(), 1000);
                    }, 1500);
                } else {
                    // Show error message
                    let errorMessage = data.message || 'An error occurred while submitting the report.';
                    if (data.errors) {
                        errorMessage = Object.values(data.errors).flat().join('<br>');
                    }
                    
                    const alert = `
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            ${errorMessage}
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    `;
                    formAlerts.insertAdjacentHTML('afterbegin', alert);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                const alert = `
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        An error occurred while submitting the report. Please try again.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                `;
                formAlerts.insertAdjacentHTML('afterbegin', alert);
            })
            .finally(() => {
                // Reset button state
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
                
                // Scroll to top to show messages
                formAlerts.scrollIntoView({ behavior: 'smooth', block: 'start' });
            });
        });
    }
    
    // Show toast notification
    function showToast(title, message, type = 'info') {
        const toastContainer = document.getElementById('toastContainer');
        if (!toastContainer) return;
        
        const toastId = 'toast-' + Date.now();
        const toast = `
            <div id="${toastId}" class="toast align-items-center text-white bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true">
                <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>
            </div>
        `;
        
        toastContainer.insertAdjacentHTML('beforeend', toast);
        const toastElement = document.getElementById(toastId);
        const toastInstance = new bootstrap.Toast(toastElement, {
            autohide: true,
            delay: 5000
        });
        toastInstance.show();
        
        // Remove toast from DOM after it's hidden
        toastElement.addEventListener('hidden.bs.toast', function() {
            toastElement.remove();
        });
    }
});
</script>
{% endblock %}
