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

{% block title %}Generate Portfolio Snapshots{% endblock %}

{% block extra_css %}
<style>
    .manager-card {
        border: 1px solid #e0e0e0;
        border-radius: 0.5rem;
        padding: 1rem;
        margin-bottom: 1rem;
        transition: all 0.3s ease;
    }
    
    .manager-card:hover {
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        border-color: #007bff;
    }
    
    .manager-card.selected {
        border-color: #007bff;
        background-color: #f8f9ff;
    }
    
    .generation-status {
        display: none;
        margin-top: 1rem;
    }
    
    .status-success {
        color: #28a745;
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        padding: 0.75rem;
        border-radius: 0.25rem;
    }
    
    .status-error {
        color: #721c24;
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        padding: 0.75rem;
        border-radius: 0.25rem;
    }
    
    .loading-spinner {
        display: none;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h3 mb-0">Generate Portfolio Snapshots</h1>
                <a href="{% url 'users:portfolio_snapshot_dashboard' %}" class="btn btn-outline-secondary">
                    <span>←</span> Back to Dashboard
                </a>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Snapshot Generation Options</h5>
                </div>
                <div class="card-body">
                    <form id="snapshotForm">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="targetDate" class="form-label">Target Date</label>
                                <input type="date" class="form-control" id="targetDate" name="date" value="{{ today|date:'Y-m-d' }}" required>
                                <div class="form-text">Date to generate snapshots for</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Generation Scope</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="scope" id="scopeAll" value="all" checked>
                                    <label class="form-check-label" for="scopeAll">
                                        All Portfolio Managers
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="scope" id="scopeSpecific" value="specific">
                                    <label class="form-check-label" for="scopeSpecific">
                                        Specific Manager
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div id="managerSelection" style="display: none;">
                            <div class="mb-3">
                                <label class="form-label">Select Portfolio Manager</label>
                                <div class="row">
                                    {% for manager in managers %}
                                    <div class="col-md-6 mb-2">
                                        <div class="manager-card" data-manager-id="{{ manager.id }}">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="manager_id" id="manager_{{ manager.id }}" value="{{ manager.id }}">
                                                <label class="form-check-label" for="manager_{{ manager.id }}">
                                                    <div class="d-flex align-items-center">
                                                        <div class="avatar-sm me-2">
                                                            <div class="avatar-title bg-primary rounded-circle">
                                                                {{ manager.first_name|first }}{{ manager.last_name|first }}
                                                            </div>
                                                        </div>
                                                        <div>
                                                            <h6 class="mb-0">{{ manager.get_full_name }}</h6>
                                                            <small class="text-muted">{{ manager.branch.name|default:"No Branch" }} - {{ manager.get_role_display }}</small>
                                                        </div>
                                                    </div>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="forceRegenerate" name="force">
                                <label class="form-check-label" for="forceRegenerate">
                                    Force regeneration of existing snapshots
                                </label>
                                <div class="form-text">Check this to overwrite existing snapshots for the selected date</div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between">
                            <button type="button" class="btn btn-outline-secondary" onclick="window.history.back()">
                                Cancel
                            </button>
                            <button type="submit" class="btn btn-primary" id="generateBtn">
                                <span class="loading-spinner spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                <span>🔄</span>
                                Generate Snapshots
                            </button>
                        </div>
                    </form>

                    <div id="generationStatus" class="generation-status"></div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">Information</h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <h6><span>ℹ️</span> About Portfolio Snapshots</h6>
                        <p class="mb-2">Portfolio snapshots capture comprehensive performance metrics for each portfolio manager, including:</p>
                        <ul class="mb-0">
                            <li>Client and loan counts</li>
                            <li>Financial metrics (disbursed, outstanding, collected)</li>
                            <li>Risk indicators (PAR, default rates)</li>
                            <li>Performance scores and growth rates</li>
                        </ul>
                    </div>

                    <div class="alert alert-warning">
                        <h6><span>⚠️</span> Important Notes</h6>
                        <ul class="mb-0">
                            <li>Snapshots are typically generated automatically daily</li>
                            <li>Manual generation should only be used for missing dates or corrections</li>
                            <li>Performance alerts will be sent based on calculated health scores</li>
                        </ul>
                    </div>

                    <div class="mt-3">
                        <h6>Quick Actions</h6>
                        <div class="d-grid gap-2">
                            <a href="{% url 'users:portfolio_snapshot_dashboard' %}" class="btn btn-outline-primary btn-sm">
                                <span>📈</span> View Dashboard
                            </a>
                            <a href="{% url 'users:portfolio_health_alerts' %}" class="btn btn-outline-warning btn-sm">
                                <span>🔔</span> View Alerts
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const scopeRadios = document.querySelectorAll('input[name="scope"]');
    const managerSelection = document.getElementById('managerSelection');
    const managerCards = document.querySelectorAll('.manager-card');
    const snapshotForm = document.getElementById('snapshotForm');
    const generateBtn = document.getElementById('generateBtn');
    const loadingSpinner = generateBtn.querySelector('.loading-spinner');
    const generationStatus = document.getElementById('generationStatus');

    // Handle scope selection
    scopeRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === 'specific') {
                managerSelection.style.display = 'block';
            } else {
                managerSelection.style.display = 'none';
                // Clear manager selection
                document.querySelectorAll('input[name="manager_id"]').forEach(input => {
                    input.checked = false;
                });
                managerCards.forEach(card => {
                    card.classList.remove('selected');
                });
            }
        });
    });

    // Handle manager card selection
    managerCards.forEach(card => {
        card.addEventListener('click', function() {
            const managerId = this.dataset.managerId;
            const radioInput = document.getElementById(`manager_${managerId}`);
            
            // Clear previous selections
            managerCards.forEach(c => c.classList.remove('selected'));
            
            // Select this card
            this.classList.add('selected');
            radioInput.checked = true;
        });
    });

    // Handle form submission
    snapshotForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const scope = formData.get('scope');
        
        // Prepare request data
        const requestData = {
            date: formData.get('date'),
            force: formData.has('force')
        };
        
        if (scope === 'specific') {
            const managerId = formData.get('manager_id');
            if (!managerId) {
                alert('Please select a portfolio manager.');
                return;
            }
            requestData.manager_id = managerId;
        }
        
        // Show loading state
        generateBtn.disabled = true;
        loadingSpinner.style.display = 'inline-block';
        generationStatus.style.display = 'none';
        
        // Send request
        fetch('{% url "users:generate_snapshot_manual" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify(requestData)
        })
        .then(response => response.json())
        .then(data => {
            // Hide loading state
            generateBtn.disabled = false;
            loadingSpinner.style.display = 'none';
            
            // Show status
            generationStatus.style.display = 'block';
            
            if (data.success) {
                generationStatus.innerHTML = `
                    <div class="status-success">
                        <span>✓</span> ${data.message}
                        ${data.health_score ? `<br><small>Health Score: ${data.health_score.toFixed(1)}%</small>` : ''}
                    </div>
                `;
                
                // Redirect to dashboard after 3 seconds
                setTimeout(() => {
                    window.location.href = '{% url "users:portfolio_snapshot_dashboard" %}';
                }, 3000);
            } else {
                generationStatus.innerHTML = `
                    <div class="status-error">
                        <span>⚠️</span> Error: ${data.error}
                    </div>
                `;
            }
        })
        .catch(error => {
            // Hide loading state
            generateBtn.disabled = false;
            loadingSpinner.style.display = 'none';
            
            // Show error
            generationStatus.style.display = 'block';
            generationStatus.innerHTML = `
                <div class="status-error">
                    <span>⚠️</span> Network error: ${error.message}
                </div>
            `;
        });
    });
});

// Add CSRF token to the form
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
if (!csrfToken) {
    const form = document.getElementById('snapshotForm');
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'csrfmiddlewaretoken';
    csrfInput.value = '{{ csrf_token }}';
    form.appendChild(csrfInput);
}
</script>
{% endblock %}