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

{% block title %}Client Management - Enhanced Dashboard{% endblock %}

{% block extra_css %}
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    .dashboard-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        padding: 24px;
        margin-bottom: 24px;
        transition: all 0.3s ease;
        border: 1px solid #e5e7eb;
    }

    .dashboard-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
    }

    .metric-card {
        background: linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%);
        color: white;
        border-radius: 12px;
        padding: 20px;
        text-align: center;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .metric-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
        transition: left 0.5s;
    }

    .metric-card:hover::before {
        left: 100%;
    }

    .metric-card:hover {
        transform: translateY(-4px) scale(1.02);
    }

    .metric-card.success {
        background: linear-gradient(135deg, #10B981 0%, #059669 100%);
    }

    .metric-card.warning {
        background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%);
    }

    .metric-card.danger {
        background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
    }

    .metric-card.info {
        background: linear-gradient(135deg, #06B6D4 0%, #0891B2 100%);
    }

    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 8px;
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
        font-weight: 500;
    }

    .export-buttons {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-bottom: 20px;
    }

    .export-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        color: white;
        padding: 10px 20px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .export-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }

    .export-btn.pdf { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }
    .export-btn.excel { background: linear-gradient(135deg, #10b981 0%, #059669 100%); }
    .export-btn.csv { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }

    .client-table {
        background: white;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    }

    .client-table thead {
        background: linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%);
    }

    .client-table thead th {
        color: white;
        font-weight: 600;
        padding: 16px 12px;
        text-align: left;
        border: none;
    }

    .client-table tbody tr {
        transition: all 0.2s ease;
        border-bottom: 1px solid #f3f4f6;
    }

    .client-table tbody tr:hover {
        background-color: #f8fafc;
        transform: scale(1.01);
    }

    .client-table tbody td {
        padding: 12px;
        vertical-align: middle;
    }

    .client-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid #e5e7eb;
    }

    .client-avatar-fallback {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: linear-gradient(135deg, #3B82F6, #1D4ED8);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: 600;
        font-size: 14px;
    }

    .status-badge {
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 500;
        text-transform: uppercase;
    }

    .status-active {
        background-color: #d1fae5;
        color: #065f46;
    }

    .status-inactive {
        background-color: #fee2e2;
        color: #991b1b;
    }

    .status-pending {
        background-color: #fef3c7;
        color: #92400e;
    }

    .chart-container {
        background: white;
        border-radius: 12px;
        padding: 24px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        margin-bottom: 24px;
    }

    .chart-tabs {
        display: flex;
        border-bottom: 2px solid #e5e7eb;
        margin-bottom: 20px;
    }

    .chart-tab {
        padding: 12px 24px;
        cursor: pointer;
        border-bottom: 2px solid transparent;
        transition: all 0.3s ease;
        font-weight: 500;
        color: #6b7280;
    }

    .chart-tab.active {
        border-bottom-color: #3B82F6;
        color: #3B82F6;
        background: rgba(59, 130, 246, 0.1);
    }

    .chart-tab:hover {
        background: rgba(59, 130, 246, 0.05);
        color: #3B82F6;
    }

    .search-filters {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        margin-bottom: 24px;
    }

    .filter-group {
        display: flex;
        gap: 16px;
        align-items: center;
        flex-wrap: wrap;
    }

    .filter-input {
        padding: 8px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.2s ease;
    }

    .filter-input:focus {
        outline: none;
        border-color: #3B82F6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    .loading-spinner {
        width: 50px;
        height: 50px;
        border: 5px solid #f3f3f3;
        border-top: 5px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
    <!-- Page Header -->
    <div class="mb-8">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-900">Client Management Dashboard</h1>
                <p class="text-gray-600 mt-1">Comprehensive client analytics and management</p>
            </div>
            <div class="flex gap-3">
                {% load permission_tags %}
                {% has_permission user 'clients' 'create' as can_create_client %}
                {% if can_create_client %}
                <a href="{% url 'users:client_create' %}" 
                   class="bg-gradient-to-r from-blue-600 to-purple-600 text-white px-6 py-3 rounded-lg font-medium hover:from-blue-700 hover:to-purple-700 transition-all transform hover:-translate-y-0.5 shadow-lg">
                    <span>+</span>Add New Client
                </a>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- Export Buttons -->
    <div class="export-buttons">
        <button onclick="exportClients('pdf')" class="export-btn pdf">
            <span>📄</span> Export PDF
        </button>
        <button onclick="exportClients('excel')" class="export-btn excel">
            <span>📊</span> Export Excel
        </button>
        <button onclick="exportClients('csv')" class="export-btn csv">
            <i class="fas fa-file-csv"></i> Export CSV
        </button>
    </div>

    <!-- Client Metrics -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <a href="{% url 'users:filtered_clients' %}?status=all" class="metric-card hover:shadow-lg transition-shadow cursor-pointer block">
            <div class="metric-value">{{ total_clients|default:0 }}</div>
            <div class="metric-label">Total Clients</div>
        </a>
        <a href="{% url 'users:filtered_clients' %}?status=active" class="metric-card success hover:shadow-lg transition-shadow cursor-pointer block">
            <div class="metric-value">{{ active_clients|default:0 }}</div>
            <div class="metric-label">Active Clients</div>
        </a>
        <a href="{% url 'users:filtered_clients' %}?status=new_this_month" class="metric-card warning hover:shadow-lg transition-shadow cursor-pointer block">
            <div class="metric-value">{{ new_clients_this_month|default:0 }}</div>
            <div class="metric-label">New This Month</div>
        </a>
        <a href="{% url 'reports:portfolio_details' %}" class="metric-card info hover:shadow-lg transition-shadow cursor-pointer block">
            <div class="metric-value">KES {{ total_portfolio|default:0|floatformat:0|intcomma }}</div>
            <div class="metric-label">Total Portfolio</div>
        </a>
    </div>

    <!-- Interactive Charts -->
    <div class="chart-container">
        <div class="chart-tabs">
            <div class="chart-tab active" onclick="showChart('demographics')">Client Demographics</div>
            <div class="chart-tab" onclick="showChart('portfolio')">Portfolio Distribution</div>
            <div class="chart-tab" onclick="showChart('performance')">Performance Metrics</div>
            <div class="chart-tab" onclick="showChart('trends')">Growth Trends</div>
        </div>
        
        <div id="chart-demographics" class="chart-content">
            <div id="demographics-chart" style="height: 400px;"></div>
        </div>
        
        <div id="chart-portfolio" class="chart-content" style="display: none;">
            <div id="portfolio-chart" style="height: 400px;"></div>
        </div>
        
        <div id="chart-performance" class="chart-content" style="display: none;">
            <div id="performance-chart" style="height: 400px;"></div>
        </div>
        
        <div id="chart-trends" class="chart-content" style="display: none;">
            <div id="trends-chart" style="height: 400px;"></div>
        </div>
    </div>

    <!-- Search and Filters -->
    <div class="search-filters">
        <div class="filter-group">
            <input type="text" id="searchInput" placeholder="Search clients..." class="filter-input" style="min-width: 250px;">
            <select id="statusFilter" class="filter-input">
                <option value="">All Status</option>
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
                <option value="pending">Pending</option>
            </select>
            <select id="branchFilter" class="filter-input">
                <option value="">All Branches</option>
                {% for branch in branches %}
                <option value="{{ branch.id }}">{{ branch.name }}</option>
                {% endfor %}
            </select>
            <button onclick="applyFilters()" class="export-btn" style="background: linear-gradient(135deg, #3B82F6 0%, #1D4ED8 100%);">
                <span>🔍</span> Apply Filters
            </button>
            <button onclick="clearFilters()" class="export-btn" style="background: linear-gradient(135deg, #6B7280 0%, #4B5563 100%);">
                <span>✕</span> Clear
            </button>
        </div>
    </div>

    <!-- Client Table -->
    <div class="dashboard-card">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold text-gray-900">Client List</h2>
            <div class="text-sm text-gray-500">
                Showing {{ clients|length }} of {{ total_clients }} clients
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="client-table w-full">
                <thead>
                    <tr>
                        <th>Client</th>
                        <th>Contact</th>
                        <th>Branch</th>
                        <th>Loans</th>
                        <th>Portfolio Value</th>
                        <th>Status</th>
                        <th>Last Activity</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="clientTableBody">
                    {% for client in clients %}
                    <tr data-client-id="{{ client.id }}" data-status="{{ client.status|default:'active' }}" data-branch="{{ client.branch.id|default:'' }}">
                        <td>
                            <div class="flex items-center">
                                {% if client.profile_picture %}
                                    <img src="{{ client.profile_picture.url }}" alt="{{ client.get_full_name }}" class="client-avatar">
                                {% else %}
                                    <div class="client-avatar-fallback">
                                        {{ client.first_name.0|upper }}{{ client.last_name.0|upper }}
                                    </div>
                                {% endif %}
                                <div class="ml-3">
                                    <div class="font-medium text-gray-900">{{ client.get_full_name }}</div>
                                    <div class="text-sm text-gray-500">ID: {{ client.id_number|default:"N/A" }}</div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="text-sm">
                                <div class="text-gray-900">{{ client.phone_number|default:"N/A" }}</div>
                                <div class="text-gray-500">{{ client.email|default:"N/A" }}</div>
                            </div>
                        </td>
                        <td>
                            <span class="text-sm text-gray-900">{{ client.branch.name|default:"N/A" }}</span>
                        </td>
                        <td>
                            <div class="text-sm">
                                <div class="text-gray-900 font-medium">{{ client.total_loans|default:0 }}</div>
                                <div class="text-gray-500">{{ client.active_loans|default:0 }} active</div>
                            </div>
                        </td>
                        <td>
                            <div class="text-sm font-medium text-gray-900">
                                KES {{ client.portfolio_value|default:0|floatformat:0|intcomma }}
                            </div>
                        </td>
                        <td>
                            <span class="status-badge status-{{ client.status|default:'active' }}">
                                {{ client.status|default:"Active"|title }}
                            </span>
                        </td>
                        <td>
                            <span class="text-sm text-gray-500">
                                {{ client.last_login|date:"M d, Y"|default:"Never" }}
                            </span>
                        </td>
                        <td>
                            <div class="flex space-x-2">
                                <a href="{% url 'users:client_detail' client.id %}" 
                                   class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="{% url 'users:client_update' client.id %}" 
                                   class="text-green-600 hover:text-green-800 text-sm font-medium">
                                    <span>✏️</span>
                                </a>
                                <button onclick="generateClientReport({{ client.id }})" 
                                        class="text-purple-600 hover:text-purple-800 text-sm font-medium">
                                    <span>📄</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="8" class="text-center py-8 text-gray-500">
                            <span>👥</span>
                            <div>No clients found</div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // Sample data for charts (replace with actual data from Django context)
    const chartData = {
        demographics: {
            age_groups: {
                '18-25': 45,
                '26-35': 120,
                '36-45': 85,
                '46-55': 60,
                '55+': 35
            },
            gender: {
                'Male': 180,
                'Female': 165
            },
            occupation: {
                'Business': 120,
                'Employment': 95,
                'Farming': 70,
                'Other': 60
            }
        },
        portfolio: {
            loan_sizes: {
                '< 50K': 85,
                '50K - 100K': 120,
                '100K - 200K': 95,
                '200K - 500K': 35,
                '500K+': 10
            },
            risk_levels: {
                'Low Risk': 220,
                'Medium Risk': 95,
                'High Risk': 30
            }
        },
        performance: {
            repayment_rates: {
                'Excellent (95-100%)': 180,
                'Good (85-94%)': 120,
                'Fair (70-84%)': 35,
                'Poor (<70%)': 10
            },
            client_retention: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                rates: [92, 94, 91, 95, 93, 96]
            }
        },
        trends: {
            monthly_growth: {
                months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                new_clients: [15, 22, 18, 28, 25, 32],
                total_clients: [280, 302, 320, 348, 373, 405]
            }
        }
    };

    document.addEventListener('DOMContentLoaded', function() {
        initializeCharts();
        setupSearch();
    });

    function initializeCharts() {
        createDemographicsChart();
        createPortfolioChart();
        createPerformanceChart();
        createTrendsChart();
    }

    function createDemographicsChart() {
        const data = chartData.demographics;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 2, cols: 2,
            subplot_titles: ['Age Distribution', 'Gender Distribution', 'Occupation Distribution', 'Client Growth'],
            specs: [[{type: 'pie'}, {type: 'pie'}], [{type: 'bar'}, {type: 'scatter'}]]
        });

        // Age distribution
        fig.add_trace({
            type: 'pie',
            labels: Object.keys(data.age_groups),
            values: Object.values(data.age_groups),
            hole: 0.4,
            marker: {colors: ['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6']}
        }, 1, 1);

        // Gender distribution
        fig.add_trace({
            type: 'pie',
            labels: Object.keys(data.gender),
            values: Object.values(data.gender),
            hole: 0.4,
            marker: {colors: ['#06B6D4', '#EC4899']}
        }, 1, 2);

        // Occupation distribution
        fig.add_trace({
            type: 'bar',
            x: Object.keys(data.occupation),
            y: Object.values(data.occupation),
            marker: {color: '#3B82F6'}
        }, 2, 1);

        // Sample growth trend
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
            y: [280, 302, 320, 348, 373, 405],
            line: {color: '#10B981', width: 3}
        }, 2, 2);

        const layout = {
            title: 'Client Demographics Overview',
            height: 400,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('demographics-chart', fig.data, layout);
    }

    function createPortfolioChart() {
        const data = chartData.portfolio;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 1, cols: 2,
            subplot_titles: ['Loan Size Distribution', 'Risk Level Distribution'],
            specs: [[{type: 'bar'}, {type: 'pie'}]]
        });

        // Loan sizes
        fig.add_trace({
            type: 'bar',
            x: Object.keys(data.loan_sizes),
            y: Object.values(data.loan_sizes),
            marker: {color: '#3B82F6'}
        }, 1, 1);

        // Risk levels
        fig.add_trace({
            type: 'pie',
            labels: Object.keys(data.risk_levels),
            values: Object.values(data.risk_levels),
            hole: 0.4,
            marker: {colors: ['#10B981', '#F59E0B', '#EF4444']}
        }, 1, 2);

        const layout = {
            title: 'Portfolio Distribution Analysis',
            height: 400,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('portfolio-chart', fig.data, layout);
    }

    function createPerformanceChart() {
        const data = chartData.performance;
        
        const fig = Plotly.subplots.make_subplots({
            rows: 1, cols: 2,
            subplot_titles: ['Repayment Performance', 'Client Retention Trend'],
            specs: [[{type: 'bar'}, {type: 'scatter'}]]
        });

        // Repayment rates
        fig.add_trace({
            type: 'bar',
            x: Object.keys(data.repayment_rates),
            y: Object.values(data.repayment_rates),
            marker: {color: ['#10B981', '#3B82F6', '#F59E0B', '#EF4444']}
        }, 1, 1);

        // Retention trend
        fig.add_trace({
            type: 'scatter',
            mode: 'lines+markers',
            x: data.client_retention.months,
            y: data.client_retention.rates,
            line: {color: '#10B981', width: 3}
        }, 1, 2);

        const layout = {
            title: 'Client Performance Metrics',
            height: 400,
            showlegend: false,
            template: 'plotly_white'
        };

        Plotly.newPlot('performance-chart', fig.data, layout);
    }

    function createTrendsChart() {
        const data = chartData.trends;
        
        const trace1 = {
            x: data.monthly_growth.months,
            y: data.monthly_growth.new_clients,
            type: 'bar',
            name: 'New Clients',
            marker: {color: '#3B82F6'}
        };

        const trace2 = {
            x: data.monthly_growth.months,
            y: data.monthly_growth.total_clients,
            type: 'scatter',
            mode: 'lines+markers',
            name: 'Total Clients',
            yaxis: 'y2',
            line: {color: '#10B981', width: 3}
        };

        const layout = {
            title: 'Client Growth Trends',
            xaxis: {title: 'Month'},
            yaxis: {title: 'New Clients'},
            yaxis2: {
                title: 'Total Clients',
                overlaying: 'y',
                side: 'right'
            },
            height: 400,
            template: 'plotly_white'
        };

        Plotly.newPlot('trends-chart', [trace1, trace2], layout);
    }

    function showChart(chartType) {
        // Hide all chart contents
        document.querySelectorAll('.chart-content').forEach(content => {
            content.style.display = 'none';
        });
        
        // Remove active class from all tabs
        document.querySelectorAll('.chart-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        
        // Show selected chart
        document.getElementById(`chart-${chartType}`).style.display = 'block';
        event.target.classList.add('active');
    }

    function setupSearch() {
        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('input', function() {
            filterTable();
        });
    }

    function filterTable() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const statusFilter = document.getElementById('statusFilter').value;
        const branchFilter = document.getElementById('branchFilter').value;
        
        const rows = document.querySelectorAll('#clientTableBody tr');
        
        rows.forEach(row => {
            const clientName = row.querySelector('td:first-child').textContent.toLowerCase();
            const clientStatus = row.dataset.status;
            const clientBranch = row.dataset.branch;
            
            let showRow = true;
            
            // Search filter
            if (searchTerm && !clientName.includes(searchTerm)) {
                showRow = false;
            }
            
            // Status filter
            if (statusFilter && clientStatus !== statusFilter) {
                showRow = false;
            }
            
            // Branch filter
            if (branchFilter && clientBranch !== branchFilter) {
                showRow = false;
            }
            
            row.style.display = showRow ? '' : 'none';
        });
    }

    function applyFilters() {
        filterTable();
    }

    function clearFilters() {
        document.getElementById('searchInput').value = '';
        document.getElementById('statusFilter').value = '';
        document.getElementById('branchFilter').value = '';
        filterTable();
    }

    function exportClients(format) {
        showLoading();
        
        // Simulate export process
        setTimeout(() => {
            hideLoading();
            
            // Create download link
            const link = document.createElement('a');
            link.href = `{% url 'users:client_list' %}?format=${format}`;
            link.download = `clients_report.${format}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }, 2000);
    }

    function generateClientReport(clientId) {
        showLoading();
        
        // Simulate report generation
        setTimeout(() => {
            hideLoading();
            
            // Open client report in new tab
            window.open(`/users/client/${clientId}/report/`, '_blank');
        }, 1500);
    }

    function showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    function hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }
</script>
{% endblock %}