<!DOCTYPE html>
<html>
<head>
    <title>Token Usage Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #0f172a;
            color: #e2e8f0;
            min-height: 100vh;
            padding: 2rem;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 3rem;
        }
        
        h1 {
            font-size: 2.5rem;
            font-weight: 700;
            background: linear-gradient(to right, #60a5fa, #a78bfa);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .back-button {
            background: #1e293b;
            color: #e2e8f0;
            border: 1px solid #334155;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-block;
        }
        
        .back-button:hover {
            background: #334155;
            border-color: #475569;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 3rem;
        }
        
        .stat-card {
            background: #1e293b;
            border: 1px solid #334155;
            border-radius: 1rem;
            padding: 2rem;
            transition: transform 0.2s;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            border-color: #475569;
        }
        
        .stat-card.cost-card {
            background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
            border-color: #10b981;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 3rem;
            font-weight: 700;
            color: #60a5fa;
        }
        
        .cost-value {
            color: #10b981;
            font-size: 2.5rem;
        }
        
        .stat-subtext {
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.5rem;
        }
        
        .chart-container {
            background: #1e293b;
            border: 1px solid #334155;
            border-radius: 1rem;
            padding: 2rem;
            margin-bottom: 3rem;
        }
        
        .chart-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 1.5rem;
            color: #e2e8f0;
        }
        
        .table-container {
            background: #1e293b;
            border: 1px solid #334155;
            border-radius: 1rem;
            padding: 2rem;
            overflow-x: auto;
            margin-bottom: 3rem;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead {
            border-bottom: 2px solid #334155;
        }
        
        th {
            text-align: left;
            padding: 1rem;
            font-size: 0.875rem;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-weight: 600;
        }
        
        td {
            padding: 1rem;
            border-bottom: 1px solid #334155;
            color: #e2e8f0;
        }
        
        tr:last-child td {
            border-bottom: none;
        }
        
        tbody tr:hover {
            background: #0f172a;
        }
        
        .total-cell {
            color: #60a5fa;
            font-weight: 600;
        }

        .charts-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 1.5rem;
            margin-bottom: 3rem;
        }

        @media (max-width: 768px) {
            .charts-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Token Usage Dashboard</h1>
            <a href="/" class="back-button">← Back to Home</a>
        </div>
        
        <!-- Token Usage Stats -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">Daily Tokens</div>
                <div class="stat-value" id="daily">0</div>
                <div class="stat-subtext" id="dailyCost">Cost: $0.00</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Weekly Tokens</div>
                <div class="stat-value" id="weekly">0</div>
                <div class="stat-subtext" id="weeklyCost">Cost: $0.00</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Monthly Tokens</div>
                <div class="stat-value" id="monthly">0</div>
                <div class="stat-subtext" id="monthlyCost">Cost: $0.00</div>
            </div>
        </div>

        <!-- Cost Summary Cards -->
        <div class="stats-grid">
            <div class="stat-card cost-card">
                <div class="stat-label">Daily Cost</div>
                <div class="stat-value cost-value" id="dailyCostMain">$0.00</div>
            </div>
            <div class="stat-card cost-card">
                <div class="stat-label">Weekly Cost</div>
                <div class="stat-value cost-value" id="weeklyCostMain">$0.00</div>
            </div>
            <div class="stat-card cost-card">
                <div class="stat-label">Monthly Cost</div>
                <div class="stat-value cost-value" id="monthlyCostMain">$0.00</div>
            </div>
        </div>

        <!-- Charts -->
        <div class="charts-row">
            <div class="chart-container">
                <h2 class="chart-title">Token Usage Overview</h2>
                <canvas id="usageChart"></canvas>
            </div>
            
            <div class="chart-container">
                <h2 class="chart-title">Cost Overview</h2>
                <canvas id="costChart"></canvas>
            </div>
        </div>
        
        <!-- Daily Usage Table -->
        <div class="table-container">
            <h2 class="chart-title">Detailed Usage by Date</h2>
            <table id="usageTable">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Prompt Tokens</th>
                        <th>Candidates Tokens</th>
                        <th>Thoughts Tokens</th>
                        <th>Total Tokens</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Rows inserted dynamically -->
                </tbody>
            </table>
        </div>

        <!-- Per User Usage Table -->
        <div class="table-container">
            <h2 class="chart-title">Token Usage by User</h2>
            <table id="userTable">
                <thead>
                    <tr>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Prompt Tokens</th>
                        <th>Candidates Tokens</th>
                        <th>Thoughts Tokens</th>
                        <th>Total Tokens</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Rows inserted dynamically -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        const token = "{{ token }}";
        const API_BASE = "https://lm.backenddb.codetorise.com";

        async function loadSummary() {
            try {
                const res = await fetch(`${API_BASE}/user/token-usage/summary/`, {
                    headers: { "Authorization": `Bearer ${token}` }
                });
                const data = await res.json();
                console.log(token);
                console.log(data);

                document.getElementById("daily").innerText = data.daily_tokens.toLocaleString();
                document.getElementById("weekly").innerText = data.weekly_tokens.toLocaleString();
                document.getElementById("monthly").innerText = data.monthly_tokens.toLocaleString();

                drawTokenChart(data);
            } catch (error) {
                console.error("Error loading summary:", error);
            }
        }

        async function loadCostEstimate() {
            try {
                const res = await fetch(`${API_BASE}/user/token-usage/cost/`, {
                    headers: { "Authorization": `Bearer ${token}` }
                });
                const data = await res.json();

                // Update cost subtexts
                document.getElementById("dailyCost").innerText = `Cost: $${data.daily.cost_usd.toFixed(4)}`;
                document.getElementById("weeklyCost").innerText = `Cost: $${data.weekly.cost_usd.toFixed(4)}`;
                document.getElementById("monthlyCost").innerText = `Cost: $${data.monthly.cost_usd.toFixed(4)}`;

                // Update main cost cards
                document.getElementById("dailyCostMain").innerText = `$${data.daily.cost_usd.toFixed(4)}`;
                document.getElementById("weeklyCostMain").innerText = `$${data.weekly.cost_usd.toFixed(4)}`;
                document.getElementById("monthlyCostMain").innerText = `$${data.monthly.cost_usd.toFixed(2)}`;

                drawCostChart(data);
            } catch (error) {
                console.error("Error loading cost estimate:", error);
            }
        }

        function drawTokenChart(data) {
            new Chart(document.getElementById("usageChart"), {
                type: 'bar',
                data: {
                    labels: ["Daily", "Weekly", "Monthly"],
                    datasets: [{
                        label: "Token Usage",
                        data: [data.daily_tokens, data.weekly_tokens, data.monthly_tokens],
                        backgroundColor: ["#60a5fa", "#a78bfa", "#f472b6"]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            labels: {
                                color: '#e2e8f0'
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                color: '#94a3b8',
                                callback: function(value) {
                                    return value.toLocaleString();
                                }
                            },
                            grid: {
                                color: '#334155'
                            }
                        },
                        x: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: '#334155'
                            }
                        }
                    }
                }
            });
        }

        function drawCostChart(data) {
            new Chart(document.getElementById("costChart"), {
                type: 'bar',
                data: {
                    labels: ["Daily", "Weekly", "Monthly"],
                    datasets: [{
                        label: "Cost (USD)",
                        data: [data.daily.cost_usd, data.weekly.cost_usd, data.monthly.cost_usd],
                        backgroundColor: ["#10b981", "#14b8a6", "#06b6d4"]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            labels: {
                                color: '#e2e8f0'
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                color: '#94a3b8',
                                callback: function(value) {
                                    return '$' + value.toFixed(2);
                                }
                            },
                            grid: {
                                color: '#334155'
                            }
                        },
                        x: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: '#334155'
                            }
                        }
                    }
                }
            });
        }

        async function loadTable() {
            try {
                const res = await fetch(`${API_BASE}/user/token-usage/list/`, {
                    headers: { "Authorization": `Bearer ${token}` }
                });
                const data = await res.json();
                const tbody = document.querySelector("#usageTable tbody");
                tbody.innerHTML = "";

                data.forEach(entry => {
                    const row = `
                        <tr>
                            <td>${entry.date}</td>
                            <td>${entry.prompt_tokens.toLocaleString()}</td>
                            <td>${entry.candidates_tokens.toLocaleString()}</td>
                            <td>${entry.thoughts_tokens.toLocaleString()}</td>
                            <td class="total-cell">${entry.total_tokens.toLocaleString()}</td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
            } catch (error) {
                console.error("Error loading table:", error);
            }
        }

        async function loadUserTable() {
            try {
                const res = await fetch(`${API_BASE}/user/token-usage/users/`, {
                    headers: { "Authorization": `Bearer ${token}` }
                });
                const data = await res.json();
                const tbody = document.querySelector("#userTable tbody");
                tbody.innerHTML = "";

                data.forEach(entry => {
                    const row = `
                        <tr>
                            <td>${entry.user__username}</td>
                            <td>${entry.user__email || 'N/A'}</td>
                            <td>${entry.prompt_tokens.toLocaleString()}</td>
                            <td>${entry.candidates_tokens.toLocaleString()}</td>
                            <td>${entry.thoughts_tokens.toLocaleString()}</td>
                            <td class="total-cell">${entry.total_tokens.toLocaleString()}</td>
                        </tr>
                    `;
                    tbody.innerHTML += row;
                });
            } catch (error) {
                console.error("Error loading user table:", error);
            }
        }

        // Load all data on page load
        loadSummary();
        loadCostEstimate();
        loadTable();
        loadUserTable();
    </script>
</body>
</html>