{% extends "base.html" %}

{% block title %}Monitoring AI - Panel Admina{% endblock %}

{% block extra_css %}
<style>
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: var(--spacing-xl);
    }

    .page-header h1 {
        font-size: var(--font-size-2xl);
    }

    /* Period filter buttons */
    .period-filters {
        display: flex;
        gap: var(--spacing-sm);
        margin-bottom: var(--spacing-xl);
        flex-wrap: wrap;
    }

    .period-btn {
        padding: var(--spacing-sm) var(--spacing-md);
        border-radius: var(--radius);
        border: 1px solid var(--border);
        background: var(--surface);
        text-decoration: none;
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        transition: var(--transition);
    }

    .period-btn:hover {
        background: var(--background);
        color: var(--text-primary);
    }

    .period-btn.active {
        background: var(--primary);
        border-color: var(--primary);
        color: white;
    }

    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: var(--spacing-lg);
        margin-bottom: var(--spacing-2xl);
    }

    .stat-card {
        background: var(--surface);
        padding: var(--spacing-lg);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow);
        text-align: center;
    }

    .stat-card.highlight {
        border-left: 4px solid var(--primary);
    }

    .stat-card.warning {
        border-left: 4px solid var(--warning);
    }

    .stat-card.success {
        border-left: 4px solid var(--success);
    }

    .stat-card.error {
        border-left: 4px solid var(--error);
    }

    .stat-card.info {
        border-left: 4px solid #6366f1;
    }

    .stat-value {
        font-size: var(--font-size-2xl);
        font-weight: 700;
        color: var(--text-primary);
    }

    .stat-value.primary { color: var(--primary); }
    .stat-value.success { color: var(--success); }
    .stat-value.warning { color: var(--warning); }
    .stat-value.error { color: var(--error); }
    .stat-value.info { color: #6366f1; }

    .stat-label {
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
        margin-top: var(--spacing-xs);
    }

    .stat-sublabel {
        color: var(--text-muted);
        font-size: var(--font-size-xs);
        margin-top: 2px;
    }

    .section {
        background: var(--surface);
        padding: var(--spacing-xl);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow);
        margin-bottom: var(--spacing-xl);
    }

    .section h2 {
        font-size: var(--font-size-xl);
        margin-bottom: var(--spacing-lg);
        color: var(--text-primary);
        border-bottom: 2px solid var(--border);
        padding-bottom: var(--spacing-sm);
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
    }

    .section h2 .icon {
        font-size: var(--font-size-2xl);
    }

    .section h2 .badge {
        font-size: var(--font-size-xs);
        background: var(--primary);
        color: white;
        padding: 2px 8px;
        border-radius: var(--radius);
        margin-left: auto;
    }

    /* Usage breakdown bars */
    .usage-breakdown {
        display: flex;
        flex-direction: column;
        gap: var(--spacing-md);
    }

    .usage-row {
        display: flex;
        align-items: center;
        gap: var(--spacing-md);
    }

    .usage-label {
        width: 120px;
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
    }

    .usage-bar-container {
        flex: 1;
        height: 24px;
        background: var(--background);
        border-radius: var(--radius);
        overflow: hidden;
    }

    .usage-bar {
        height: 100%;
        border-radius: var(--radius);
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-right: var(--spacing-sm);
        font-size: var(--font-size-xs);
        font-weight: 600;
        color: white;
        min-width: 40px;
        transition: width 0.3s ease;
    }

    .usage-bar.chat { background: #3b82f6; }
    .usage-bar.news { background: #10b981; }
    .usage-bar.user { background: #f59e0b; }
    .usage-bar.image { background: #8b5cf6; }
    .usage-bar.other { background: #6b7280; }

    .usage-count {
        width: 60px;
        text-align: right;
        font-weight: 600;
        font-size: var(--font-size-sm);
    }

    /* Ranking tables */
    .ranking-table {
        width: 100%;
        border-collapse: collapse;
    }

    .ranking-table th,
    .ranking-table td {
        padding: var(--spacing-md);
        text-align: left;
        border-bottom: 1px solid var(--border);
    }

    .ranking-table th {
        background: var(--background);
        font-weight: 600;
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
    }

    .ranking-table tr:hover {
        background: var(--background);
    }

    .ranking-position {
        width: 40px;
        text-align: center;
        font-weight: 700;
        color: var(--text-muted);
    }

    .ranking-position.top-1 { color: #f59e0b; }
    .ranking-position.top-2 { color: #94a3b8; }
    .ranking-position.top-3 { color: #b45309; }

    .user-info {
        display: flex;
        flex-direction: column;
    }

    .user-name {
        font-weight: 600;
        color: var(--text-primary);
    }

    .user-company {
        font-size: var(--font-size-xs);
        color: var(--text-secondary);
    }

    .user-info-link {
        text-decoration: none;
        display: block;
        padding: var(--spacing-xs);
        margin: calc(-1 * var(--spacing-xs));
        border-radius: var(--radius-sm);
        transition: var(--transition);
    }

    .user-info-link:hover {
        background: var(--primary-light, #eff6ff);
    }

    .user-info-link:hover .user-name {
        color: var(--primary);
    }

    .cost-badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: var(--radius-sm);
        font-size: var(--font-size-xs);
        font-weight: 500;
        background: #dcfce7;
        color: #166534;
    }

    .cost-badge.medium {
        background: #fef3c7;
        color: #92400e;
    }

    .cost-badge.high {
        background: #fee2e2;
        color: #991b1b;
    }

    /* Cost bar visualization */
    .cost-bar-container {
        width: 100px;
        height: 8px;
        background: var(--border);
        border-radius: 4px;
        overflow: hidden;
    }

    .cost-bar {
        height: 100%;
        background: linear-gradient(90deg, #10b981, #f59e0b, #ef4444);
        border-radius: 4px;
    }

    /* Recent logs */
    .log-list {
        list-style: none;
        max-height: 400px;
        overflow-y: auto;
    }

    .log-item {
        padding: var(--spacing-md);
        border-bottom: 1px solid var(--border);
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: var(--spacing-md);
    }

    .log-item:last-child {
        border-bottom: none;
    }

    .log-info {
        display: flex;
        flex-direction: column;
        gap: 2px;
    }

    .log-type {
        display: inline-block;
        padding: 2px 8px;
        border-radius: var(--radius-sm);
        font-size: var(--font-size-xs);
        font-weight: 500;
    }

    .log-type.chat { background: #dbeafe; color: #1d4ed8; }
    .log-type.news_evaluation { background: #d1fae5; color: #065f46; }
    .log-type.user_creation { background: #fef3c7; color: #92400e; }
    .log-type.image_analysis { background: #ede9fe; color: #5b21b6; }
    .log-type.other { background: #f3f4f6; color: #374151; }

    .log-user {
        font-size: var(--font-size-xs);
        color: var(--text-secondary);
    }

    .log-meta {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 2px;
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
    }

    .log-tokens {
        font-family: monospace;
    }

    .log-time {
        color: var(--text-muted);
        font-size: var(--font-size-xs);
    }

    .log-error {
        color: var(--error);
        font-size: var(--font-size-xs);
    }

    /* Empty state */
    .empty-state {
        text-align: center;
        padding: var(--spacing-2xl);
        color: var(--text-secondary);
    }

    .empty-state .icon {
        font-size: 48px;
        margin-bottom: var(--spacing-md);
    }

    /* Two column layout for sections */
    .sections-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
        gap: var(--spacing-xl);
    }

    /* Daily history table */
    .daily-table {
        width: 100%;
        border-collapse: collapse;
        font-size: var(--font-size-sm);
    }

    .daily-table th,
    .daily-table td {
        padding: var(--spacing-sm) var(--spacing-md);
        text-align: left;
        border-bottom: 1px solid var(--border);
    }

    .daily-table th {
        background: var(--background);
        font-weight: 600;
        color: var(--text-secondary);
    }

    .daily-table tr:hover {
        background: var(--background);
    }

    @media (max-width: 768px) {
        .sections-grid {
            grid-template-columns: 1fr;
        }
        .usage-label {
            width: 80px;
        }
        .ranking-table {
            font-size: var(--font-size-sm);
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="page-header">
    <div>
        <h1>Monitoring AI</h1>
        <p class="text-muted">Statystyki wykorzystania Gemini API</p>
    </div>
    <a href="{{ url_for('dashboard') }}" class="btn btn-secondary">Powrót</a>
</div>

<!-- Period Filters -->
<div class="period-filters">
    <span class="text-muted" style="padding: var(--spacing-sm) 0;">Okres:</span>
    <a href="{{ url_for('admin_ai_usage', period='day') }}" class="period-btn {% if current_period == 'day' %}active{% endif %}">Dzisiaj</a>
    <a href="{{ url_for('admin_ai_usage', period='week') }}" class="period-btn {% if current_period == 'week' %}active{% endif %}">Tydzień</a>
    <a href="{{ url_for('admin_ai_usage', period='month') }}" class="period-btn {% if current_period == 'month' %}active{% endif %}">Miesiąc</a>
    <a href="{{ url_for('admin_ai_usage', period='all') }}" class="period-btn {% if current_period == 'all' %}active{% endif %}">Od początku</a>
</div>

<!-- Main Stats -->
<div class="stats-grid">
    <div class="stat-card highlight">
        <div class="stat-value primary">{{ stats.today_requests }}</div>
        <div class="stat-label">Dzisiaj</div>
        <div class="stat-sublabel">zapytań</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ stats.week_requests }}</div>
        <div class="stat-label">Tydzień</div>
        <div class="stat-sublabel">zapytań</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ stats.month_requests }}</div>
        <div class="stat-label">Miesiąc</div>
        <div class="stat-sublabel">zapytań</div>
    </div>
    <div class="stat-card info">
        <div class="stat-value info">{{ stats.all_requests }}</div>
        <div class="stat-label">Od początku</div>
        <div class="stat-sublabel">zapytań</div>
    </div>
    <div class="stat-card success">
        <div class="stat-value success">${{ "%.4f"|format(stats.today_cost) }}</div>
        <div class="stat-label">Koszt dziś</div>
        <div class="stat-sublabel">USD</div>
    </div>
    <div class="stat-card warning">
        <div class="stat-value warning">${{ "%.4f"|format(stats.month_cost) }}</div>
        <div class="stat-label">Koszt miesiąc</div>
        <div class="stat-sublabel">USD</div>
    </div>
    <div class="stat-card info">
        <div class="stat-value info">${{ "%.4f"|format(stats.all_cost) }}</div>
        <div class="stat-label">Koszt całkowity</div>
        <div class="stat-sublabel">USD</div>
    </div>
    <div class="stat-card {% if stats.error_rate > 10 %}error{% elif stats.error_rate > 5 %}warning{% else %}success{% endif %}">
        <div class="stat-value {% if stats.error_rate > 10 %}error{% elif stats.error_rate > 5 %}warning{% else %}success{% endif %}">{{ "%.1f"|format(stats.error_rate) }}%</div>
        <div class="stat-label">Błędy</div>
        <div class="stat-sublabel">24h</div>
    </div>
</div>

<!-- Token Stats -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-value">{{ "{:,}".format(stats.today_tokens_input) }}</div>
        <div class="stat-label">Tokeny input</div>
        <div class="stat-sublabel">dzisiaj</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ "{:,}".format(stats.today_tokens_output) }}</div>
        <div class="stat-label">Tokeny output</div>
        <div class="stat-sublabel">dzisiaj</div>
    </div>
    <div class="stat-card">
        <div class="stat-value">{{ stats.avg_response_time }}ms</div>
        <div class="stat-label">Avg czas</div>
        <div class="stat-sublabel">24h</div>
    </div>
</div>

<!-- User and Company Rankings -->
<div class="sections-grid">
    <!-- User Rankings -->
    <div class="section">
        <h2>
            <span class="icon">👤</span> Ranking użytkowników
            <span class="badge">{{ period_label }}</span>
        </h2>
        {% if user_rankings %}
        <table class="ranking-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Użytkownik</th>
                    <th>Zapytania</th>
                    <th>Tokeny</th>
                    <th>Koszt</th>
                </tr>
            </thead>
            <tbody>
                {% for user in user_rankings %}
                <tr>
                    <td class="ranking-position {% if loop.index == 1 %}top-1{% elif loop.index == 2 %}top-2{% elif loop.index == 3 %}top-3{% endif %}">
                        {{ loop.index }}
                    </td>
                    <td>
                        <a href="{{ url_for('admin_ai_usage_user', user_id=user.id) }}" class="user-info-link">
                            <div class="user-info">
                                <span class="user-name">{{ user.name }}</span>
                                <span class="user-company">{{ user.company }}</span>
                            </div>
                        </a>
                    </td>
                    <td>{{ user.requests }}</td>
                    <td>{{ "{:,}".format(user.tokens) }}</td>
                    <td>
                        <span class="cost-badge {% if user.cost_cents > 100 %}high{% elif user.cost_cents > 10 %}medium{% endif %}">
                            ${{ "%.4f"|format(user.cost_usd) }}
                        </span>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <div class="empty-state">
            <div class="icon">👤</div>
            <p>Brak danych o użytkownikach</p>
        </div>
        {% endif %}
    </div>

    <!-- Company Rankings -->
    <div class="section">
        <h2>
            <span class="icon">🏢</span> Ranking firm
            <span class="badge">{{ period_label }}</span>
        </h2>
        {% if company_rankings %}
        <table class="ranking-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Firma</th>
                    <th>Użytkownicy</th>
                    <th>Zapytania</th>
                    <th>Koszt</th>
                </tr>
            </thead>
            <tbody>
                {% for company in company_rankings %}
                <tr>
                    <td class="ranking-position {% if loop.index == 1 %}top-1{% elif loop.index == 2 %}top-2{% elif loop.index == 3 %}top-3{% endif %}">
                        {{ loop.index }}
                    </td>
                    <td>
                        <span class="user-name">{{ company.name }}</span>
                    </td>
                    <td>{{ company.unique_users }}</td>
                    <td>{{ company.requests }}</td>
                    <td>
                        <span class="cost-badge {% if company.cost_cents > 100 %}high{% elif company.cost_cents > 10 %}medium{% endif %}">
                            ${{ "%.4f"|format(company.cost_usd) }}
                        </span>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <div class="empty-state">
            <div class="icon">🏢</div>
            <p>Brak danych o firmach</p>
        </div>
        {% endif %}
    </div>
</div>

<div class="sections-grid">
    <!-- Usage by Type -->
    <div class="section">
        <h2>
            <span class="icon">📊</span> Wykorzystanie wg typu
            <span class="badge">{{ period_label }}</span>
        </h2>
        {% if usage_by_type %}
        <div class="usage-breakdown">
            {% for item in usage_by_type %}
            <div class="usage-row">
                <div class="usage-label">{{ item.type_label }}</div>
                <div class="usage-bar-container">
                    <div class="usage-bar {{ item.type_class }}" style="width: {{ item.percentage }}%">
                        {{ item.percentage }}%
                    </div>
                </div>
                <div class="usage-count">{{ item.count }}</div>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="empty-state">
            <div class="icon">📭</div>
            <p>Brak danych</p>
        </div>
        {% endif %}
    </div>

    <!-- Recent Logs -->
    <div class="section">
        <h2><span class="icon">📜</span> Ostatnie zapytania</h2>
        {% if recent_logs %}
        <ul class="log-list">
            {% for log in recent_logs %}
            <li class="log-item">
                <div class="log-info">
                    <span class="log-type {{ log.request_type }}">{{ log.type_label }}</span>
                    {% if log.user_name %}
                    <span class="log-user">{{ log.user_name }}</span>
                    {% endif %}
                    {% if not log.success %}
                    <span class="log-error">{{ log.error_message[:30] }}...</span>
                    {% endif %}
                </div>
                <div class="log-meta">
                    <span class="log-tokens">{{ log.tokens_input or 0 }}+{{ log.tokens_output or 0 }}</span>
                    <span class="log-time">{{ log.created_at.strftime('%d.%m %H:%M') }}</span>
                </div>
            </li>
            {% endfor %}
        </ul>
        {% else %}
        <div class="empty-state">
            <p>Brak ostatnich zapytań</p>
        </div>
        {% endif %}
    </div>
</div>

<!-- Daily History -->
<div class="section">
    <h2><span class="icon">📅</span> Historia dzienna (ostatnie 14 dni)</h2>
    {% if daily_history %}
    <table class="daily-table">
        <thead>
            <tr>
                <th>Data</th>
                <th>Zapytania</th>
                <th>Chat</th>
                <th>News</th>
                <th>Tokeny</th>
                <th>Koszt</th>
                <th>Błędy</th>
            </tr>
        </thead>
        <tbody>
            {% for day in daily_history %}
            <tr>
                <td>{{ day.date.strftime('%d.%m.%Y') }}</td>
                <td><strong>{{ day.total_requests }}</strong></td>
                <td>{{ day.chat_requests }}</td>
                <td>{{ day.news_evaluation_requests }}</td>
                <td>{{ "{:,}".format(day.total_tokens or 0) }}</td>
                <td>
                    <span class="cost-badge {% if (day.total_cost_cents or 0) > 10 %}high{% elif (day.total_cost_cents or 0) > 1 %}medium{% endif %}">
                        ${{ "%.4f"|format((day.total_cost_cents or 0) / 100) }}
                    </span>
                </td>
                <td>{% if day.error_count > 0 %}<span style="color: var(--error)">{{ day.error_count }}</span>{% else %}-{% endif %}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {% else %}
    <div class="empty-state">
        <div class="icon">📭</div>
        <p>Brak historii - dane pojawią się po pierwszym użyciu AI</p>
    </div>
    {% endif %}
</div>
{% endblock %}
