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

{% block title %}Client Assignment - Simple{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50">
    <!-- Header -->
    <div class="bg-white shadow">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-6">
                <div>
                    <h1 class="text-2xl font-bold text-gray-900">Client Assignment</h1>
                    <p class="text-sm text-gray-600">Assign, unassign, and reassign clients to portfolio managers</p>
                </div>
                <div class="flex space-x-3">
                    <a href="{% url 'users:portfolio_dashboard' %}" 
                       class="bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-lg text-sm font-medium">
                        Back to Dashboard
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        <!-- Messages -->
        {% if messages %}
            {% for message in messages %}
                <div class="mb-4 p-4 rounded-md {% if message.tags == 'error' %}bg-red-50 text-red-700 border border-red-200{% elif message.tags == 'success' %}bg-green-50 text-green-700 border border-green-200{% else %}bg-blue-50 text-blue-700 border border-blue-200{% endif %}">
                    {{ message }}
                </div>
            {% endfor %}
        {% endif %}

        <!-- Branch Filter -->
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 mb-6">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">Filter by Branch</h3>
            </div>
            <div class="p-6">
                <form method="get" class="flex items-center space-x-4">
                    <select name="branch" class="block w-64 rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
                        <option value="">All Branches</option>
                        {% for branch in branches %}
                        <option value="{{ branch.id }}" {% if selected_branch_id == branch.id|stringformat:"s" %}selected{% endif %}>
                            {{ branch.name }}
                        </option>
                        {% endfor %}
                    </select>
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                        Filter
                    </button>
                </form>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Unassigned Clients -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">
                        Unassigned Clients ({{ unassigned_clients.count }})
                    </h3>
                </div>
                <div class="p-6">
                    {% if unassigned_clients %}
                        <div class="space-y-3 max-h-96 overflow-y-auto">
                            {% for client in unassigned_clients %}
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <div class="flex-1">
                                    <div class="font-medium text-gray-900">{{ client.get_full_name }}</div>
                                    <div class="text-sm text-gray-600">{{ client.email|default:"No email" }}</div>
                                    {% if client.business_name %}
                                    <div class="text-sm text-gray-500">{{ client.business_name }}</div>
                                    {% endif %}
                                </div>
                                <div class="flex space-x-2">
                                    <button onclick="assignClient('{{ client.id }}', '{{ client.get_full_name }}')" 
                                            class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm">
                                        Assign
                                    </button>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center py-8 text-gray-500">
                            <span>👥</span>
                            <p>No unassigned clients found</p>
                        </div>
                    {% endif %}
                </div>
            </div>

            <!-- Portfolio Managers -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">
                        Portfolio Managers ({{ portfolio_managers.count }})
                    </h3>
                </div>
                <div class="p-6">
                    {% if portfolio_managers %}
                        <div class="space-y-3 max-h-96 overflow-y-auto">
                            {% for manager in portfolio_managers %}
                            <div class="p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center justify-between mb-2">
                                    <div class="font-medium text-gray-900">{{ manager.get_full_name }}</div>
                                    <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                                        {{ manager.get_role_display }}
                                    </span>
                                </div>
                                <div class="text-sm text-gray-600 mb-2">
                                    {{ manager.client_count }} clients assigned
                                </div>
                                <div class="flex space-x-2">
                                    <button onclick="viewManagerClients('{{ manager.id }}', '{{ manager.get_full_name }}')" 
                                            class="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm">
                                        View Clients
                                    </button>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    {% else %}
                        <div class="text-center py-8 text-gray-500">
                            <span>👔</span>
                            <p>No portfolio managers found</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Assignment Modal -->
<div id="assignmentModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 class="text-lg font-medium text-gray-900 mb-4" id="modalTitle">Assign Client</h3>
            <div class="mb-4">
                <p class="text-sm text-gray-600" id="modalClientName"></p>
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">Select Manager:</label>
                <select id="managerSelect" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm">
                    <option value="">Choose a manager...</option>
                    {% for manager in portfolio_managers %}
                    <option value="{{ manager.id }}">{{ manager.get_full_name }} ({{ manager.get_role_display }})</option>
                    {% endfor %}
                </select>
            </div>
            <div class="flex justify-end space-x-3">
                <button onclick="closeModal()" class="bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded text-sm">
                    Cancel
                </button>
                <button onclick="confirmAssignment()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm">
                    Assign
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Manager Clients Modal -->
<div id="managerClientsModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-10 mx-auto p-5 border w-4/5 max-w-4xl shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 class="text-lg font-medium text-gray-900 mb-4" id="managerModalTitle">Manager's Clients</h3>
            <div id="managerClientsList" class="space-y-3 max-h-96 overflow-y-auto">
                <!-- Clients will be loaded here -->
            </div>
            <div class="flex justify-end mt-4">
                <button onclick="closeManagerModal()" class="bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded text-sm">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentClientId = null;
let currentClientName = null;

function assignClient(clientId, clientName) {
    currentClientId = clientId;
    currentClientName = clientName;
    document.getElementById('modalTitle').textContent = 'Assign Client';
    document.getElementById('modalClientName').textContent = `Assigning: ${clientName}`;
    document.getElementById('managerSelect').value = '';
    document.getElementById('assignmentModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('assignmentModal').classList.add('hidden');
    currentClientId = null;
    currentClientName = null;
}

function confirmAssignment() {
    const managerId = document.getElementById('managerSelect').value;
    if (!managerId) {
        alert('Please select a manager');
        return;
    }
    
    if (!currentClientId) {
        alert('No client selected');
        return;
    }
    
    // Create form and submit
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '{% url "users:assign_clients" %}';
    
    // Add CSRF token
    const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    const csrfInput = document.createElement('input');
    csrfInput.type = 'hidden';
    csrfInput.name = 'csrfmiddlewaretoken';
    csrfInput.value = csrfToken;
    form.appendChild(csrfInput);
    
    // Add client ID
    const clientInput = document.createElement('input');
    clientInput.type = 'hidden';
    clientInput.name = 'client_ids';
    clientInput.value = currentClientId;
    form.appendChild(clientInput);
    
    // Add manager ID
    const managerInput = document.createElement('input');
    managerInput.type = 'hidden';
    managerInput.name = 'manager_id';
    managerInput.value = managerId;
    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();
}

function viewManagerClients(managerId, managerName) {
    document.getElementById('managerModalTitle').textContent = `${managerName}'s Clients`;
    
    // Fetch manager's clients
    fetch(`/api/manager-clients/${managerId}/`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            const clientsList = document.getElementById('managerClientsList');
            if (data.clients && data.clients.length > 0) {
                clientsList.innerHTML = data.clients.map(client => `
                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div class="flex-1">
                            <div class="font-medium text-gray-900">${client.name}</div>
                            <div class="text-sm text-gray-600">${client.email || 'No email'}</div>
                        </div>
                        <div class="flex space-x-2">
                            <button onclick="reassignClient('${client.id}', '${client.name}', '${managerId}', '${managerName}')" 
                                    class="bg-yellow-600 hover:bg-yellow-700 text-white px-3 py-1 rounded text-sm">
                                Reassign
                            </button>
                            <button onclick="unassignClient('${client.id}', '${client.name}')" 
                                    class="bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm">
                                Unassign
                            </button>
                        </div>
                    </div>
                `).join('');
            } else {
                clientsList.innerHTML = '<div class="text-center py-8 text-gray-500">No clients assigned to this manager</div>';
            }
        })
        .catch(error => {
            console.error('Error fetching manager clients:', error);
            document.getElementById('managerClientsList').innerHTML = '<div class="text-center py-8 text-red-500">Error loading clients. Please try again.</div>';
        });
    
    document.getElementById('managerClientsModal').classList.remove('hidden');
}

function closeManagerModal() {
    document.getElementById('managerClientsModal').classList.add('hidden');
}

function reassignClient(clientId, clientName, currentManagerId, currentManagerName) {
    currentClientId = clientId;
    currentClientName = clientName;
    document.getElementById('modalTitle').textContent = 'Reassign Client';
    document.getElementById('modalClientName').textContent = `Reassigning: ${clientName} (currently with ${currentManagerName})`;
    
    // Filter out current manager from options
    const managerSelect = document.getElementById('managerSelect');
    managerSelect.innerHTML = '<option value="">Choose a new manager...</option>';
    {% for manager in portfolio_managers %}
    if ('{{ manager.id }}' !== currentManagerId) {
        const option = document.createElement('option');
        option.value = '{{ manager.id }}';
        option.textContent = '{{ manager.get_full_name }} ({{ manager.get_role_display }})';
        managerSelect.appendChild(option);
    }
    {% endfor %}
    
    document.getElementById('assignmentModal').classList.remove('hidden');
    closeManagerModal();
}

function unassignClient(clientId, clientName) {
    if (confirm(`Are you sure you want to unassign ${clientName}?`)) {
        // Create form and submit
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = '{% url "users:assign_clients" %}';
        
        // Add CSRF token
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = 'csrfmiddlewaretoken';
        csrfInput.value = csrfToken;
        form.appendChild(csrfInput);
        
        // Add client ID
        const clientInput = document.createElement('input');
        clientInput.type = 'hidden';
        clientInput.name = 'client_ids';
        clientInput.value = clientId;
        form.appendChild(clientInput);
        
        // Add unassign flag
        const unassignInput = document.createElement('input');
        unassignInput.type = 'hidden';
        unassignInput.name = 'action';
        unassignInput.value = 'unassign';
        form.appendChild(unassignInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

<!-- Add CSRF token for JavaScript -->
{% csrf_token %}
{% endblock %}
