{% extends "base.html" %}
{% block title %}Планировщик — TG Agent{% endblock %}
{% block content %}
<h1>Планировщик</h1>

{% macro task_type_label(t) %}
    {% if t.task_type.value == 'channel_collect' %}Сбор канала
    {% elif t.task_type.value == 'stats_all' %}Статистика
    {% elif t.task_type.value == 'sq_stats' %}Статистика запроса
    {% elif t.task_type.value == 'photo_due' %}Фото
    {% elif t.task_type.value == 'photo_auto' %}Автофото
    {% else %}{{ t.task_type.value }}
    {% endif %}
{% endmacro %}

<div class="card mb-4">
    <div class="card-header fw-semibold">
        Планировщик
        <span class="hint" data-tooltip="Планировщик автоматически ставит задачи в очередь: сбор, статистику">?</span>
    </div>
    <div class="card-body">
        <small class="text-muted d-block mb-2">Автоматическое создание задач: сбор каждые {{ interval_minutes }} мин.</small>
        <p>Статус: <strong>{{ "Запущен" if is_running else "Остановлен" }}</strong></p>

        <div class="d-flex flex-wrap gap-2">
            {% if not is_running %}
            <form method="post" action="/scheduler/start" data-busy>
                <button type="submit" class="btn btn-primary">&#9654; Запустить</button>
            </form>
            {% else %}
            <form method="post" action="/scheduler/stop" data-busy>
                <button type="submit" class="btn btn-secondary">&#9724; Остановить</button>
            </form>
            {% endif %}
            <form method="post" action="/scheduler/trigger" data-busy>
                <button type="submit" class="btn btn-outline-primary">&#9654; Собрать все каналы</button>
            </form>
            {% if pending_collect_count > 0 %}
            <form method="post" action="/scheduler/tasks/clear-pending-collect" data-busy>
                <button type="submit" class="btn btn-outline-danger">
                    Очистить очередь загрузки ({{ pending_collect_count }})
                </button>
            </form>
            {% endif %}
            <form method="post" action="/scheduler/test-notification" data-busy>
                <button type="submit" class="btn btn-outline-secondary"
                        {% if not bot_configured %}disabled title="Подключите бот в Настройках → Уведомления"{% endif %}>
                    Тест
                </button>
            </form>
            <button type="button" class="btn btn-outline-info"
                    onclick="dryRunNotifications()"
                    id="dry-run-btn">
                Dry-run
            </button>
        </div>
    </div>
</div>

<!-- Scheduler Jobs -->
{% if scheduler_jobs %}
<div class="card mb-4">
    <div class="card-header fw-semibold">
        Джобы планировщика
        <span class="badge text-bg-secondary ms-1">{{ scheduler_jobs|length }}</span>
        {% if not is_running %}
        <small class="text-muted ms-2">(будут зарегистрированы при запуске)</small>
        {% endif %}
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
        <table class="table table-sm table-striped mb-0">
            <thead>
                <tr>
                    <th>Вкл.</th>
                    <th>Джоб</th>
                    <th>Интервал</th>
                    <th>Следующий запуск</th>
                </tr>
            </thead>
            <tbody>
                {% for j in scheduler_jobs %}
                <tr>
                    <td>
                        <form method="post" action="/scheduler/jobs/{{ j.job_id }}/toggle" class="mb-0">
                            <input type="checkbox" onchange="this.form.submit()"
                                   {% if j.enabled %}checked{% endif %}
                                   title="{{ 'Отключить' if j.enabled else 'Включить' }}">
                        </form>
                    </td>
                    <td class="{% if not j.enabled %}text-muted{% endif %}">{{ j.label }}</td>
                    <td>
                        {% if j.interval_editable and j.interval_minutes is not none %}
                            <form method="post" action="/scheduler/jobs/{{ j.job_id }}/set-interval"
                                  class="d-flex gap-1 mb-0">
                                <input type="number" name="interval_minutes" value="{{ j.interval_minutes }}"
                                       min="1" max="1440" class="form-control form-control-sm" style="width:75px">
                                <button type="submit" class="btn btn-sm btn-outline-secondary">✓</button>
                            </form>
                        {% elif j.interval_minutes %}
                            {{ j.interval_minutes }} мин.
                        {% else %}
                            —
                        {% endif %}
                    </td>
                    <td>
                        {% if j.next_run %}
                            {{ j.next_run|local_dt("time") }}
                        {% elif is_running and j.enabled %}
                            —
                        {% elif not j.enabled %}
                            <span class="text-muted">отключён</span>
                        {% else %}
                            <span class="text-muted">остановлен</span>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </div>
    </div>
</div>
{% endif %}

<!-- Dry-run results (populated via fetch) -->
<div id="dry-run-results" class="mb-4" style="display:none"></div>

{% if search_log %}
<div class="card mb-4">
    <div class="card-header fw-semibold">
        Лог поиска
        <span class="hint" data-tooltip="Последние результаты поиска: какой запрос, сколько найдено, каким аккаунтом">?</span>
    </div>
    <div class="card-body p-0">
        <!-- Desktop -->
        <div class="table-responsive d-none d-md-block">
        <table class="table table-striped table-sm mb-0">
            <thead>
                <tr>
                    <th>Запрос</th>
                    <th>Аккаунт</th>
                    <th>Результатов</th>
                    <th>Дата</th>
                </tr>
            </thead>
            <tbody>
                {% for entry in search_log %}
                <tr>
                    <td>{{ entry.query }}</td>
                    <td>{{ entry.phone }}</td>
                    <td>{{ entry.results_count }}</td>
                    <td>{{ entry.created_at|local_dt }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </div>
        <!-- Mobile -->
        <div class="d-md-none mobile-cards p-2">
            {% for entry in search_log %}
            <div class="card mb-2">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <strong class="text-truncate">{{ entry.query }}</strong>
                        <span class="badge text-bg-secondary">{{ entry.results_count }}</span>
                    </div>
                    <small class="text-muted">{{ entry.phone }} &middot; {{ entry.created_at|local_dt }}</small>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</div>
{% endif %}

{% if all_count > 0 %}
<div class="card mb-4">
    <div class="card-header fw-semibold">Задачи</div>
    <div class="card-body p-0">
        <p class="px-3 pt-3"><small class="text-muted">Все задачи: сбор каналов, статистика, фото.</small></p>

        <!-- Filter tabs -->
        <div class="px-3 pb-2">
            <div class="btn-group" role="tablist">
                <a href="/scheduler?status=all&page=1&limit={{ limit }}" class="btn btn-sm {% if status_filter == 'all' %}btn-primary{% else %}btn-outline-primary{% endif %}">
                    Все ({{ all_count }})
                </a>
                <a href="/scheduler?status=active&page=1&limit={{ limit }}" class="btn btn-sm {% if status_filter == 'active' %}btn-primary{% else %}btn-outline-primary{% endif %}">
                    Активные ({{ active_count }})
                </a>
                <a href="/scheduler?status=completed&page=1&limit={{ limit }}" class="btn btn-sm {% if status_filter == 'completed' %}btn-primary{% else %}btn-outline-primary{% endif %}">
                    Завершенные ({{ completed_count }})
                </a>
            </div>
        </div>

        {% if tasks %}
        <!-- Desktop -->
        <div class="table-responsive d-none d-md-block">
        <table class="table table-striped table-sm mb-0">
            <thead>
                <tr>
                    <th>Тип</th>
                    <th>Канал / Описание</th>
                    <th>Статус</th>
                    <th>Результат</th>
                    <th>Создана</th>
                    <th>Завершена</th>
                    <th>Действие</th>
                </tr>
            </thead>
            <tbody>
                {% for t in tasks %}
                <tr>
                    <td><span class="badge text-bg-info">{{ task_type_label(t) }}</span></td>
                    <td>
                        {{ t.channel_title or t.channel_id or '—' }}
                        {% if t.channel_username %}
                        <br><small class="text-muted">@{{ t.channel_username }}</small>
                        {% endif %}
                    </td>
                    <td>
                        {% if t.status == 'running' %}
                            <span class="spinner-border spinner-border-sm" role="status"></span> Выполняется
                        {% elif t.status == 'completed' %}
                            Завершено
                            {% if t.note %}<br><small class="text-muted">{{ t.note }}</small>{% endif %}
                        {% elif t.status == 'failed' %}
                            <span class="badge text-bg-danger">Ошибка</span>
                            {% if t.error %}<br><small>{{ t.error[:100] }}</small>{% endif %}
                        {% elif t.status == 'cancelled' %}
                            Отменена
                        {% else %}
                            {% if t.run_after %}
                                Ожидание до {{ t.run_after|local_dt }}
                            {% else %}
                                Ожидание
                            {% endif %}
                        {% endif %}
                    </td>
                    <td>
                        {% if t.task_type == 'stats_all' and t.payload and t.payload.channel_ids %}
                            {{ t.messages_collected }}/{{ t.payload.channel_ids|length }}
                        {% else %}
                            {{ t.messages_collected }}
                        {% endif %}
                    </td>
                    <td>{{ t.created_at|local_dt }}</td>
                    <td>{{ t.completed_at|local_dt }}</td>
                    <td>
                        {% if t.status == 'running' %}
                            <form method="post" action="/scheduler/tasks/{{ t.id }}/cancel" class="mb-0" data-busy>
                                <button type="submit" class="btn btn-outline-secondary btn-sm">Отменить</button>
                            </form>
                        {% elif t.status == 'pending' %}
                            <form method="post" action="/scheduler/tasks/{{ t.id }}/cancel" class="mb-0" data-busy>
                                <button type="submit" class="btn btn-outline-secondary btn-sm">Удалить</button>
                            </form>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        </div>
        <!-- Mobile -->
        <div class="d-md-none mobile-cards p-2">
            {% for t in tasks %}
            <div class="card mb-2">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                        <div>
                            <span class="badge text-bg-info me-1">{{ task_type_label(t) }}</span>
                            <strong>{{ t.channel_title or t.channel_id or '—' }}</strong>
                            {% if t.channel_username %}<br><small class="text-muted">@{{ t.channel_username }}</small>{% endif %}
                        </div>
                        <span>
                            {% if t.status == 'running' %}
                                <span class="spinner-border spinner-border-sm" role="status"></span>
                            {% elif t.status == 'completed' %}
                                <span class="badge text-bg-success">OK</span>
                            {% elif t.status == 'failed' %}
                                <span class="badge text-bg-danger">Ошибка</span>
                            {% elif t.status == 'cancelled' %}
                                <span class="badge text-bg-secondary">Отменена</span>
                            {% else %}
                                <span class="badge text-bg-warning">Ожидание</span>
                            {% endif %}
                        </span>
                    </div>
                    <small class="text-muted">
                        {% if t.task_type == 'stats_all' and t.payload and t.payload.channel_ids %}
                            {{ t.messages_collected }}/{{ t.payload.channel_ids|length }}
                        {% else %}
                            {{ t.messages_collected }} сообщ.
                        {% endif %}
                        {% if t.created_at %}&middot; {{ t.created_at|local_dt }}{% endif %}
                    </small>
                    {% if t.status == 'running' or t.status == 'pending' %}
                    <div class="mt-1">
                        <form method="post" action="/scheduler/tasks/{{ t.id }}/cancel" class="mb-0" data-busy>
                            <button type="submit" class="btn btn-outline-secondary btn-sm">{{ 'Отменить' if t.status == 'running' else 'Удалить' }}</button>
                        </form>
                    </div>
                    {% endif %}
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- Pagination -->
        {% if total_pages > 1 %}
        <nav>
            <ul class="pagination justify-content-center mb-0">
                {% if page > 1 %}
                <li class="page-item"><a class="page-link" href="/scheduler?status={{ status_filter }}&page={{ page - 1 }}&limit={{ limit }}">Назад</a></li>
                {% endif %}
                <li class="page-item disabled"><span class="page-link">Страница {{ page }} из {{ total_pages }}</span></li>
                {% if page < total_pages %}
                <li class="page-item"><a class="page-link" href="/scheduler?status={{ status_filter }}&page={{ page + 1 }}&limit={{ limit }}">Далее</a></li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
        {% else %}
        <p class="text-muted text-center py-3">Нет задач с выбранным фильтром.</p>
        {% endif %}
    </div>
</div>
{% endif %}

<script>
{% if has_active_tasks %}
setTimeout(function() {
    window.location.reload();
}, 5000);
{% endif %}

function dryRunNotifications() {
    var btn = document.getElementById('dry-run-btn');
    var container = document.getElementById('dry-run-results');
    setAsyncButtonBusy(btn, true, 'Dry-run');
    fetch('/scheduler/dry-run-notifications', {method: 'POST'})
        .then(function(r) { return r.text(); })
        .then(function(html) {
            container.innerHTML = html;
            container.style.display = '';
        })
        .catch(function() {
            container.innerHTML = '<div class="alert alert-danger">Ошибка при выполнении dry-run</div>';
            container.style.display = '';
        })
        .finally(function() {
            setAsyncButtonBusy(btn, false);
        });
}
</script>
{% endblock %}
