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

{% block title %}Advanced Client Assignment Center{% endblock %}

{% block extra_head %}
<link href="https://cdn.tailwindcss.com/3.4.17" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
<style>
    .gradient-bg {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    .card-hover {
        transition: all 0.3s ease;
    }
    
    .card-hover:hover {
        transform: translateY(-2px);
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }
    
    .client-card {
        @apply border-2 border-gray-200 rounded-xl p-4 mb-3 cursor-pointer transition-all duration-300 hover:border-blue-500 hover:shadow-lg;
    }
    
    .client-card.selected {
        @apply border-blue-500 bg-gradient-to-r from-blue-50 to-blue-100 transform scale-105 shadow-lg;
    }
    
    .manager-card {
        @apply border-2 border-gray-200 rounded-xl p-5 mb-4 cursor-pointer transition-all duration-300 hover:border-green-500 hover:shadow-lg;
    }
    
    .manager-card.selected {
        @apply border-green-500 bg-gradient-to-r from-green-50 to-green-100 transform scale-105 shadow-lg;
    }
    
    .pulse-animation {
        animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.5; }
    }
    
    .fade-in {
        animation: fadeIn 0.5s ease-in;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .stat-card {
        @apply bg-white rounded-xl shadow-sm border border-gray-200 p-6 card-hover;
    }
    
    .progress-bar {
        @apply w-full bg-gray-200 rounded-full h-2.5;
    }
    
    .progress-fill {
        @apply bg-blue-600 h-2.5 rounded-full transition-all duration-500;
    }
</style>
{% endblock %}

{% block content %}
{% csrf_token %}
<div class="min-h-screen bg-gray-50" x-data="assignmentApp()">
    <!-- Enhanced Header Section -->
    <div class="gradient-bg text-black py-16">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="text-center">
                <div class="inline-flex items-center justify-center w-20 h-20 bg-white bg-opacity-20 rounded-full mb-6">
                    <i class="fas fa-users-cog text-4xl"></i>
                </div>
                <h1 class="text-5xl font-bold mb-6">Advanced Client Assignment Center</h1>
                    <p class="text-xl text-black max-w-3xl mx-auto mb-8">
                    Intelligently assign clients to portfolio managers with advanced matching algorithms, real-time analytics, and comprehensive portfolio insights
                </p>
                
                <!-- Branch Selector -->
                <div class="max-w-md mx-auto">
                    <label class="block text-sm font-medium text-blue-100 mb-2">Filter by Branch</label>
                    <select x-model="selectedBranch" @change="filterByBranch()" class="w-full px-4 py-3 rounded-lg bg-white bg-opacity-20 border border-white border-opacity-30 text-white placeholder-blue-200 focus:outline-none focus:ring-2 focus:ring-white focus:ring-opacity-50">
                        <option value="">All Branches</option>
                        {% for branch in branch_stats.all_branches %}
                        <option value="{{ branch.id }}" {% if branch.id == selected_branch_id %}selected{% endif %}>{{ branch.name }}</option>
                        {% endfor %}
                    </select>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
        <!-- Enhanced Statistics Dashboard -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="stat-card">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-user-clock text-blue-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <div class="text-3xl font-bold text-gray-900">{{ stats.total_unassigned }}</div>
                        <div class="text-sm text-gray-600">Unassigned Clients</div>
                        <div class="text-xs text-blue-600 mt-1">{{ branch_stats.current_branch.name|default:"All Branches" }}</div>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                        <span>👔</span>
                    </div>
                    <div class="ml-4">
                        <div class="text-3xl font-bold text-gray-900">{{ stats.total_managers }}</div>
                        <div class="text-sm text-gray-600">Available Managers</div>
                        <div class="text-xs text-green-600 mt-1">Active Portfolio Managers</div>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-percentage text-purple-600 text-xl"></i>
                    </div>
                    <div class="ml-4">
                        <div class="text-3xl font-bold text-gray-900">{{ stats.assignment_rate }}%</div>
                        <div class="text-sm text-gray-600">Assignment Rate</div>
                        <div class="progress-bar mt-2">
                            <div class="progress-fill" style="width: {{ stats.assignment_rate }}%"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                        <span>👥</span>
                    </div>
                    <div class="ml-4">
                        <div class="text-3xl font-bold text-gray-900">{{ stats.total_clients_in_branch }}</div>
                        <div class="text-sm text-gray-600">Total Clients</div>
                        <div class="text-xs text-orange-600 mt-1">{{ stats.assigned_clients_count }} assigned</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Portfolio Analytics Dashboard -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
            <!-- Portfolio Performance Chart -->
            <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                    <span>📈</span>
                    Portfolio Performance Overview
                </h3>
                <canvas id="portfolioChart" width="400" height="200"></canvas>
            </div>

            <!-- Manager Workload Distribution -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                    <i class="fas fa-balance-scale mr-3 text-green-600"></i>
                    Workload Distribution
                </h3>
                <div class="space-y-4">
                    {% for analytics in portfolio_analytics %}
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-3">
                            <div class="w-8 h-8 bg-gradient-to-r from-green-500 to-green-600 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                                {{ analytics.manager.first_name|first }}{{ analytics.manager.last_name|first }}
                            </div>
                            <div>
                                <div class="font-medium text-gray-900 text-sm">{{ analytics.manager.get_full_name }}</div>
                                <div class="text-xs text-gray-500">{{ analytics.manager.role|title }}</div>
                            </div>
                        </div>
                        <div class="text-right">
                            <div class="font-semibold text-gray-900">{{ analytics.client_count }}</div>
                            <div class="text-xs text-gray-500">clients</div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- Main Assignment Interface -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Enhanced Unassigned Clients Section -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 fade-in">
                <div class="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-blue-100">
                    <div class="flex items-center justify-between">
                        <h2 class="text-xl font-semibold text-gray-800 flex items-center">
                            <span>👥</span>
                            Unassigned Clients ({{ stats.total_unassigned }})
                        </h2>
                        <div class="flex items-center space-x-2">
                            <input type="text" x-model="clientSearch" placeholder="Search clients..." class="text-sm px-3 py-1 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <button @click="selectAllClients()" class="text-sm bg-blue-100 text-blue-700 px-3 py-1 rounded-full hover:bg-blue-200 transition-colors">
                                Select All
                            </button>
                            <button @click="clearClientSelection()" class="text-sm bg-gray-100 text-gray-700 px-3 py-1 rounded-full hover:bg-gray-200 transition-colors">
                                Clear
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="p-6">
                    <div class="space-y-3 max-h-96 overflow-y-auto" id="clients-container">
                        {% for client in unassigned_clients %}
                        <div class="client-card" data-client-id="{{ client.id }}" @click="toggleClientSelection($event)" x-show="filterClient('{{ client.get_full_name|lower }}', '{{ client.phone_number }}', '{{ client.branch.name|default:""|lower }}')">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center space-x-3">
                                    <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-blue-600 rounded-full flex items-center justify-center text-white font-semibold">
                                        {{ client.first_name|first }}{{ client.last_name|first }}
                                    </div>
                                    <div>
                                        <div class="font-semibold text-gray-900">{{ client.get_full_name }}</div>
                                        <div class="text-sm text-gray-600">{{ client.phone_number }}</div>
                                        {% if client.branch %}
                                        <div class="text-xs text-blue-600">{{ client.branch.name }}</div>
                                        {% else %}
                                        <div class="text-xs text-gray-500">No Branch Assigned</div>
                                        {% endif %}
                                        {% if client.loans.exists %}
                                        <div class="text-xs text-green-600">{{ client.loans.count }} loan(s)</div>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <div class="w-4 h-4 border-2 border-gray-300 rounded-full client-checkbox"></div>
                                    <span>›</span>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="text-center py-12 text-gray-500">
                            <span>✓</span>
                            <p class="text-xl font-medium">All clients are assigned!</p>
                            <p class="text-sm">No unassigned clients found in the current branch.</p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>

            <!-- Enhanced Portfolio Managers Section -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 fade-in">
                <div class="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-green-50 to-green-100">
                    <h2 class="text-xl font-semibold text-gray-800 flex items-center">
                        <span>👔</span>
                        Portfolio Managers ({{ stats.total_managers }})
                    </h2>
                </div>
                
                <div class="p-6">
                    <div class="space-y-4 max-h-96 overflow-y-auto" id="managers-container">
                        {% for manager in portfolio_managers %}
                        <div class="manager-card" data-manager-id="{{ manager.id }}" @click="selectManager($event)">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center space-x-3">
                                    <div class="w-14 h-14 bg-gradient-to-r from-green-500 to-green-600 rounded-full flex items-center justify-center text-white font-semibold">
                                        {{ manager.first_name|first }}{{ manager.last_name|first }}
                                    </div>
                                    <div class="flex-1">
                                        <div class="font-semibold text-gray-900">{{ manager.get_full_name }}</div>
                                        <div class="text-sm text-gray-600">{{ manager.role|title }}</div>
                                        {% if manager.branch %}
                                        <div class="text-xs text-green-600">{{ manager.branch.name }}</div>
                                        {% endif %}
                                        <div class="flex items-center space-x-4 mt-2">
                                            <div class="text-xs text-gray-500">
                                                <span>👥</span>{{ manager.branch_client_count }} clients
                                            </div>
                                            <div class="text-xs text-gray-500">
                                                <span>💵</span>KSh {{ manager.total_portfolio_value|floatformat:0 }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <div class="w-4 h-4 border-2 border-gray-300 rounded-full manager-checkbox"></div>
                                    <span>›</span>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="text-center py-12 text-gray-500">
                            <span>⚠️</span>
                            <p class="text-xl font-medium">No managers available</p>
                            <p class="text-sm">Please add portfolio managers first.</p>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- Enhanced Assignment Actions -->
        <div class="mt-8 bg-white rounded-xl shadow-sm border border-gray-200 fade-in">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                    <i class="fas fa-tasks mr-3 text-purple-600"></i>
                    Assignment Actions
                </h3>
            </div>
            
            <div class="p-6">
                <div class="flex flex-col lg:flex-row items-center justify-between space-y-4 lg:space-y-0">
                    <div class="flex items-center space-x-4">
                        <div class="text-sm text-gray-600">
                            <span x-text="selectedClients.size + ' clients'">0 clients</span> selected for assignment to 
                            <span x-text="selectedManagerName || 'no manager'" class="font-semibold text-gray-900">no manager</span>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-3">
                        <button @click="clearAllSelections()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                            <span>✕</span>Clear All
                        </button>
                        <button @click="showBulkAssignment()" class="px-4 py-2 bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors">
                            <i class="fas fa-magic mr-2"></i>Smart Assign
                        </button>
                        <button @click="assignClients()" x-bind:disabled="selectedClients.size === 0 || !selectedManager" class="px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-lg hover:from-blue-700 hover:to-blue-800 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
                            <span>👤+</span>Assign Clients
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Assignments with Enhanced Data -->
        {% if recent_assignments %}
        <div class="mt-8 bg-white rounded-xl shadow-sm border border-gray-200 fade-in">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                    <i class="fas fa-history mr-3 text-indigo-600"></i>
                    Recent Assignments (Last 30 Days)
                </h3>
            </div>
            
            <div class="p-6">
                <div class="space-y-3">
                    {% for assignment in recent_assignments %}
                    <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center">
                                <span>👤</span>
                            </div>
                            <div>
                                <div class="font-medium text-gray-900">{{ assignment.client.get_full_name }}</div>
                                <div class="text-sm text-gray-600">Assigned to {{ assignment.portfolio_manager.get_full_name }}</div>
                                <div class="text-xs text-gray-500">by {{ assignment.assigned_by.get_full_name }}</div>
                            </div>
                        </div>
                        <div class="text-right">
                            <div class="text-sm text-gray-500">{{ assignment.assigned_date|date:"M d, Y" }}</div>
                            <div class="text-xs text-gray-400">{{ assignment.assigned_date|time:"H:i" }}</div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Enhanced Assignment Modal -->
<div id="assignment-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50" x-show="showModal" x-transition>
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">Confirm Assignment</h3>
            </div>
            <div class="p-6">
                <p class="text-gray-600 mb-4">Are you sure you want to assign the selected clients to the selected manager?</p>
                <div class="flex items-center justify-end space-x-3">
                    <button @click="closeModal()" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors">
                        Cancel
                    </button>
                    <button @click="confirmAssignment()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                        Confirm Assignment
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function assignmentApp() {
    return {
        selectedClients: new Set(),
        selectedManager: null,
        selectedManagerName: null,
        selectedBranch: '{{ selected_branch_id }}',
        clientSearch: '',
        showModal: false,
        
        toggleClientSelection(event) {
            const clientId = event.currentTarget.dataset.clientId;
            const checkbox = event.currentTarget.querySelector('.client-checkbox');
            
            if (this.selectedClients.has(clientId)) {
                this.selectedClients.delete(clientId);
                event.currentTarget.classList.remove('selected');
                checkbox.classList.remove('bg-blue-500', 'border-blue-500');
                checkbox.innerHTML = '';
            } else {
                this.selectedClients.add(clientId);
                event.currentTarget.classList.add('selected');
                checkbox.classList.add('bg-blue-500', 'border-blue-500');
                checkbox.innerHTML = '<span>✓</span>';
            }
        },
        
        selectAllClients() {
            const clientCards = document.querySelectorAll('.client-card[data-client-id]');
            clientCards.forEach(card => {
                if (!card.classList.contains('selected')) {
                    this.toggleClientSelection({ currentTarget: card });
                }
            });
        },
        
        clearClientSelection() {
            this.selectedClients.clear();
            document.querySelectorAll('.client-card').forEach(card => {
                card.classList.remove('selected');
                const checkbox = card.querySelector('.client-checkbox');
                checkbox.classList.remove('bg-blue-500', 'border-blue-500');
                checkbox.innerHTML = '';
            });
        },
        
        selectManager(event) {
            // Clear previous selection
            document.querySelectorAll('.manager-card').forEach(card => {
                card.classList.remove('selected');
                const checkbox = card.querySelector('.manager-checkbox');
                checkbox.classList.remove('bg-green-500', 'border-green-500');
                checkbox.innerHTML = '';
            });
            
            // Select new manager
            this.selectedManager = event.currentTarget.dataset.managerId;
            this.selectedManagerName = event.currentTarget.querySelector('.font-semibold').textContent;
            event.currentTarget.classList.add('selected');
            const checkbox = event.currentTarget.querySelector('.manager-checkbox');
            checkbox.classList.add('bg-green-500', 'border-green-500');
            checkbox.innerHTML = '<span>✓</span>';
        },
        
        clearAllSelections() {
            this.clearClientSelection();
            this.selectedManager = null;
            this.selectedManagerName = null;
            document.querySelectorAll('.manager-card').forEach(card => {
                card.classList.remove('selected');
                const checkbox = card.querySelector('.manager-checkbox');
                checkbox.classList.remove('bg-green-500', 'border-green-500');
                checkbox.innerHTML = '';
            });
        },
        
        filterClient(name, phone, branch) {
            if (!this.clientSearch) return true;
            const search = this.clientSearch.toLowerCase();
            return name.includes(search) || phone.includes(search) || branch.includes(search);
        },
        
        filterByBranch() {
            // This would trigger a page reload with the new branch filter
            if (this.selectedBranch) {
                window.location.href = `{% url "users:assign_clients" %}?branch=${this.selectedBranch}`;
            } else {
                window.location.href = '{% url "users:assign_clients" %}';
            }
        },
        
        showBulkAssignment() {
            // Implement smart assignment logic
            alert('Smart assignment feature coming soon!');
        },
        
        assignClients() {
            if (this.selectedClients.size === 0 || !this.selectedManager) {
                alert('Please select clients and a manager first.');
                return;
            }
            this.showModal = true;
        },
        
        closeModal() {
            this.showModal = false;
        },
        
        confirmAssignment() {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '{% url "users:assign_clients" %}';
            
            // Add CSRF token
            const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
            if (csrfToken) {
                const csrfInput = document.createElement('input');
                csrfInput.type = 'hidden';
                csrfInput.name = 'csrfmiddlewaretoken';
                csrfInput.value = csrfToken.value;
                form.appendChild(csrfInput);
            }
            
            // Add client IDs
            this.selectedClients.forEach(clientId => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'client_ids';
                input.value = clientId;
                form.appendChild(input);
            });
            
            // Add manager ID
            const managerInput = document.createElement('input');
            managerInput.type = 'hidden';
            managerInput.name = 'manager_id';
            managerInput.value = this.selectedManager;
            form.appendChild(managerInput);
            
            // Add assignment type
            const typeInput = document.createElement('input');
            typeInput.type = 'hidden';
            typeInput.name = 'assignment_type';
            typeInput.value = 'manual';
            form.appendChild(typeInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    }
}

// Initialize portfolio chart
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('portfolioChart').getContext('2d');
    const portfolioData = {{ portfolio_analytics|safe }};
    
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: portfolioData.map(item => item.manager.get_full_name),
            datasets: [{
                label: 'Client Count',
                data: portfolioData.map(item => item.client_count),
                backgroundColor: 'rgba(59, 130, 246, 0.5)',
                borderColor: 'rgba(59, 130, 246, 1)',
                borderWidth: 1
            }, {
                label: 'Portfolio Value (KSh)',
                data: portfolioData.map(item => item.total_value / 1000),
                backgroundColor: 'rgba(16, 185, 129, 0.5)',
                borderColor: 'rgba(16, 185, 129, 1)',
                borderWidth: 1,
                yAxisID: 'y1'
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    grid: {
                        drawOnChartArea: false,
                    },
                }
            }
        }
    });
});
</script>
{% endblock %}