{% extends "base.jinja2" %}

{% block head_extra %}
<style>
.cost-table {
    width: 100%;
    border-collapse: collapse;
}
.cost-table th, .cost-table td {
    padding: 8px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}
.cost-table th {
    background-color: #f5f5f5;
}
.cost-form {
    max-width: 800px;
    margin: 20px 0;
}
.form-group {
    margin-bottom: 15px;
}
.form-group label {
    display: block;
    margin-bottom: 5px;
}
.form-group input, .form-group select {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}
.btn {
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
}
.btn-primary {
    background-color: #007bff;
    color: white;
    border: none;
}
.btn-primary:hover {
    background-color: #0056b3;
}
</style>
{% endblock %}

{% block content %}
<div class="content-wrapper">
    <h1>Usage Tracking Administration</h1>

    <section class="cost-config-section">
        <h2>Cost Configuration</h2>
        
        <table class="cost-table">
            <thead>
                <tr>
                    <th>Plugin</th>
                    <th>Cost Type</th>
                    <th>Unit</th>
                    <th>Default Cost</th>
                    <th>Model-Specific Costs</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                {% for plugin_id, plugin_costs in current_costs.items() %}
                    {% for cost_type_id, cost_info in plugin_costs.items() %}
                        <tr>
                            <td>{{ plugin_id }}</td>
                            <td>{{ cost_type_id }}</td>
                            <td>{{ cost_types[cost_type_id].unit if cost_type_id in cost_types else 'unknown' }}</td>
                            <td>${{ "%.6f"|format(cost_info.get('default', 0)) }}</td>
                            <td>
                                {% if cost_info.get('model_specific') %}
                                    {% for model_id, model_cost in cost_info['model_specific'].items() %}
                                        {{ model_id }}: ${{ "%.6f"|format(model_cost) }}<br>
                                    {% endfor %}
                                {% endif %}
                            </td>
                            <td>
                                <button onclick="editCost('{{ plugin_id }}', '{{ cost_type_id }}', {{ cost_info.get('default', 0) }})">
                                    Edit
                                </button>
                            </td>
                        </tr>
                    {% endfor %}
                {% endfor %}
            </tbody>
        </table>

        <form id="costForm" class="cost-form" onsubmit="updateCost(event)">
            <div class="form-group">
                <label for="pluginId">Plugin ID</label>
                <input type="text" id="pluginId" name="plugin_id" required>
            </div>
            <div class="form-group">
                <label for="costTypeId">Cost Type</label>
                <select id="costTypeId" name="cost_type_id" required>
                    {% for type_id, info in cost_types.items() %}
                        <option value="{{ type_id }}">{{ info.description }} ({{ info.unit }})</option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="unitCost">Default Cost per Unit</label>
                <input type="number" id="unitCost" name="unit_cost" step="0.000001" required>
            </div>
            <div class="form-group">
                <label for="modelId">Model ID (optional)</label>
                <input type="text" id="modelId" name="model_id">
            </div>
            <button type="submit" class="btn btn-primary">Update Cost</button>
        </form>
    </section>

    <section class="usage-report-section">
        <h2>Usage Reports</h2>
        
        <form id="reportForm" class="cost-form" onsubmit="generateReport(event)">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="startDate">Start Date</label>
                <input type="date" id="startDate" name="start_date">
            </div>
            <div class="form-group">
                <label for="endDate">End Date</label>
                <input type="date" id="endDate" name="end_date">
            </div>
            <div class="form-group">
                <label for="reportType">Report Type</label>
                <select id="reportType" name="report_type">
                    <option value="summary">Summary</option>
                    <option value="detailed">Detailed</option>
                    <option value="daily">Daily Breakdown</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Generate Report</button>
        </form>

        <div id="reportResults" style="display: none;">
            <h3>Report Results</h3>
            <pre id="reportOutput" style="background: #f5f5f5; padding: 15px; overflow-x: auto;"></pre>
        </div>
    </section>
</div>

<script>
async function updateCost(event) {
    event.preventDefault();
    const form = event.target;
    const data = {
        plugin_id: form.plugin_id.value,
        cost_type_id: form.cost_type_id.value,
        unit_cost: parseFloat(form.unit_cost.value),
        model_id: form.model_id.value || null
    };

    try {
        const response = await fetch('/api/admin/usage/costs', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (response.ok) {
            alert('Cost updated successfully');
            location.reload();
        } else {
            const error = await response.json();
            alert(`Error: ${error.detail}`);
        }
    } catch (error) {
        alert(`Error: ${error.message}`);
    }
}

function editCost(pluginId, costTypeId, unitCost) {
    document.getElementById('pluginId').value = pluginId;
    document.getElementById('costTypeId').value = costTypeId;
    document.getElementById('unitCost').value = unitCost;
    document.getElementById('modelId').value = '';
}

async function generateReport(event) {
    event.preventDefault();
    const form = event.target;
    const username = form.username.value;
    const startDate = form.start_date.value;
    const endDate = form.end_date.value;
    const reportType = form.report_type.value;

    let url = `/api/admin/usage/`;
    switch (reportType) {
        case 'summary':
            url += `summary/${username}`;
            break;
        case 'detailed':
            url += `report/${username}`;
            break;
        case 'daily':
            url += `daily/${username}`;
            break;
    }

    const params = new URLSearchParams();
    if (startDate) params.append('start_date', startDate);
    if (endDate) params.append('end_date', endDate);
    if (params.toString()) url += `?${params.toString()}`;

    try {
        const response = await fetch(url);
        const data = await response.json();
        
        const resultsDiv = document.getElementById('reportResults');
        resultsDiv.style.display = 'block';
        document.getElementById('reportOutput').textContent = 
            JSON.stringify(data, null, 2);
    } catch (error) {
        alert(`Error: ${error.message}`);
    }
}
</script>
{% endblock %}
