{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}
<div class="px-6 py-4">
    <!-- Page Header -->
    <div class="mb-8 flex justify-between items-center">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">Token Usage Report</h1>
            <p class="text-gray-600 dark:text-gray-400">Multi-dimensional token consumption analytics</p>
        </div>
        <div>
            <form method="get" class="flex gap-2 items-center">
                <label class="text-sm text-gray-600 dark:text-gray-400">Time Period:</label>
                <select name="days" onchange="this.form.submit()" class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="7" {% if days_filter == 7 %}selected{% endif %}>Last 7 Days</option>
                    <option value="30" {% if days_filter == 30 %}selected{% endif %}>Last 30 Days</option>
                    <option value="60" {% if days_filter == 60 %}selected{% endif %}>Last 60 Days</option>
                    <option value="90" {% if days_filter == 90 %}selected{% endif %}>Last 90 Days</option>
                </select>
            </form>
        </div>
    </div>

    <!-- Summary Cards -->
    {% if total_tokens == 0 %}
    <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-6 mb-8">
        <div class="flex items-start gap-3">
            <svg class="w-6 h-6 text-yellow-600 dark:text-yellow-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <div>
                <h3 class="text-lg font-semibold text-yellow-900 dark:text-yellow-200 mb-2">No Token Data Available Yet</h3>
                <p class="text-yellow-800 dark:text-yellow-300 mb-2">Historical logs (before system upgrade) don't have token data. Token tracking started after the recent backend update.</p>
                <p class="text-yellow-700 dark:text-yellow-400 text-sm">
                    <strong>Next steps:</strong> Trigger any AI operation (content generation, clustering, etc.) and token data will start appearing here automatically.
                </p>
            </div>
        </div>
    </div>
    {% endif %}
    
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Total Tokens</h3>
            <p class="text-3xl font-bold {% if total_tokens == 0 %}text-gray-400{% else %}text-gray-900 dark:text-white{% endif %}">{{ total_tokens|floatformat:0 }}</p>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ total_calls }} API calls</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Avg Tokens/Call</h3>
            <p class="text-3xl font-bold {% if avg_tokens_per_call == 0 %}text-gray-400{% else %}text-gray-900 dark:text-white{% endif %}">{{ avg_tokens_per_call|floatformat:0 }}</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Success Rate</h3>
            <p class="text-3xl font-bold text-green-600 dark:text-green-400">{{ success_rate }}%</p>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ successful_tokens|floatformat:0 }} tokens</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Total Cost</h3>
            <p class="text-3xl font-bold text-gray-900 dark:text-white">${{ total_cost|floatformat:2 }}</p>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">${{ cost_per_1k_tokens|floatformat:4 }} per 1K</p>
        </div>
    </div>

    <!-- Token Trends Chart -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Token Usage Trends</h2>
        <canvas id="tokenTrendsChart" height="80"></canvas>
    </div>

    <!-- Two Column Layout -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
        <!-- Token Usage by Model -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Token Usage by Model</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Model</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Tokens</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Calls</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Cost</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                        {% for item in token_by_model %}
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">{{ item.model|default:"Unknown" }}</td>
                            <td class="px-4 py-3 text-sm text-right text-gray-900 dark:text-white">{{ item.total_tokens|floatformat:0 }}</td>
                            <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">{{ item.call_count }}</td>
                            <td class="px-4 py-3 text-sm text-right text-gray-900 dark:text-white">${{ item.total_cost|floatformat:2 }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Token Usage by Function -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Token Usage by Function</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Function</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Tokens</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Calls</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                        {% for item in token_by_function %}
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">{{ item.function|default:"Unknown" }}</td>
                            <td class="px-4 py-3 text-sm text-right text-gray-900 dark:text-white">{{ item.total_tokens|floatformat:0 }}</td>
                            <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">{{ item.call_count }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Top Token Consumers -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Top Token Consumers (By Account)</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead>
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Account</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total Tokens</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">API Calls</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total Cost</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Avg Tokens</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    {% for consumer in token_by_account %}
                    <tr>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">
                            <a href="/admin/igny8_core_auth/account/{{ consumer.account_id }}/" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                                {{ consumer.account__name|default:"Unknown Account" }}
                            </a>
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-900 dark:text-white font-semibold">{{ consumer.total_tokens|floatformat:0 }}</td>
                        <td class="px-6 py-4 text-sm text-right text-gray-600 dark:text-gray-400">{{ consumer.call_count }}</td>
                        <td class="px-6 py-4 text-sm text-right text-gray-900 dark:text-white">${{ consumer.total_cost|floatformat:2 }}</td>
                        <td class="px-6 py-4 text-sm text-right text-gray-600 dark:text-gray-400">
                            {% widthratio consumer.total_tokens consumer.call_count 1 %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>

    <!-- Efficiency Metrics -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Efficiency Metrics</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
                <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Successful Tokens</h3>
                <p class="text-2xl font-bold text-green-600 dark:text-green-400">{{ successful_tokens|floatformat:0 }}</p>
                <div class="mt-2 w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                    <div class="bg-green-600 dark:bg-green-400 h-2 rounded-full" style="width: {{ success_rate }}%"></div>
                </div>
            </div>
            <div>
                <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Wasted Tokens</h3>
                <p class="text-2xl font-bold text-red-600 dark:text-red-400">{{ wasted_tokens|floatformat:0 }}</p>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">From failed requests</p>
            </div>
            <div>
                <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Hourly Peak Usage</h3>
                <p class="text-2xl font-bold text-blue-600 dark:text-blue-400">
                    {% for hour in hourly_usage %}
                        {% if forloop.first or hour.token_count > hourly_usage.0.token_count %}
                            {{ hour.hour|floatformat:0 }}:00
                        {% endif %}
                    {% endfor %}
                </p>
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Most active hour</p>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Token Trends Chart
    const ctx = document.getElementById('tokenTrendsChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: {{ daily_labels|safe }},
            datasets: [{
                label: 'Daily Token Usage',
                data: {{ daily_data|safe }},
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value.toLocaleString();
                        }
                    }
                }
            }
        }
    });
</script>
{% endblock %}
