{% extends "mainapp/base.html" %}
{% load static %}

{% block title %}Наличие сигнала объектов{% endblock %}

{% block extra_css %}
<style>
    .sticky-top {
        position: sticky;
        top: 0;
        z-index: 10;
    }
    
    .source-info-cell {
        min-width: 200px;
        background-color: #f8f9fa;
    }
    
    .param-cell {
        min-width: 120px;
        text-align: center;
    }
    
    .marks-cell {
        min-width: 150px;
        text-align: center;
    }
    
    .actions-cell {
        min-width: 180px;
        text-align: center;
    }
    
    .mark-status {
        font-size: 1.1rem;
    }
    
    .mark-present {
        color: #28a745;
        font-weight: 600;
    }
    
    .mark-absent {
        color: #dc3545;
        font-weight: 600;
    }
    
    .action-buttons {
        display: flex;
        flex-direction: column;
        gap: 8px;
        align-items: center;
    }
    
    .btn-mark {
        padding: 6px 16px;
        font-size: 0.875rem;
        min-width: 100px;
    }
    
    .btn-edit-mark {
        padding: 2px 8px;
        font-size: 0.75rem;
    }
    
    .no-marks {
        color: #6c757d;
        font-style: italic;
        text-align: center;
    }
    
    .btn-mark:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
    
    .btn-edit-mark:disabled {
        opacity: 0.5;
        cursor: wait;
    }
    
    .mark-status {
        transition: color 0.3s ease;
    }
    
    .btn-edit-mark:hover:not(:disabled) {
        background-color: #6c757d;
        color: white;
    }
    
    .satellite-selector {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .satellite-selector h5 {
        margin-bottom: 1rem;
        color: #495057;
    }
</style>
{% endblock %}

{% block content %}
<div class="{% if full_width_page %}container-fluid{% else %}container{% endif %} px-3">
    <!-- Page Header -->
    <div class="row mb-3">
        <div class="col-12">
            <h2>Наличие сигнала объектов</h2>
        </div>
    </div>

    <!-- Satellite Selector -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="satellite-selector">
                <h5>Выберите спутник:</h5>
                <div class="row">
                    <div class="col-md-6">
                        <select id="satellite-select" class="form-select" onchange="selectSatellite()">
                            <option value="">-- Выберите спутник --</option>
                            {% for satellite in satellites %}
                            <option value="{{ satellite.id }}" {% if satellite.id == selected_satellite_id %}selected{% endif %}>
                                {{ satellite.name }}
                            </option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {% if selected_satellite_id %}
    <!-- Toolbar with search, pagination, and filters -->
    <div class="row mb-3">
        <div class="col-12">
            {% include 'mainapp/components/_toolbar.html' with show_search=True show_filters=True show_actions=False search_placeholder='Поиск по ID или имени объекта...' %}
        </div>
    </div>

    <!-- Main Table -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body p-0">
                    <div class="table-responsive" style="max-height: 75vh; overflow-y: auto;">
                        <table class="table table-striped table-hover table-sm table-bordered mb-0">
                            <thead class="table-dark sticky-top">
                                <tr>
                                    <th class="source-info-cell">
                                        {% include 'mainapp/components/_sort_header.html' with field='id' label='ID / Имя' current_sort=sort %}
                                    </th>
                                    <th class="param-cell">
                                        {% include 'mainapp/components/_sort_header.html' with field='frequency' label='Частота, МГц' current_sort=sort %}
                                    </th>
                                    <th class="param-cell">
                                        {% include 'mainapp/components/_sort_header.html' with field='freq_range' label='Полоса, МГц' current_sort=sort %}
                                    </th>
                                    <th class="param-cell">Поляризация</th>
                                    <th class="param-cell">Модуляция</th>
                                    <th class="param-cell">
                                        {% include 'mainapp/components/_sort_header.html' with field='bod_velocity' label='Бодовая скорость' current_sort=sort %}
                                    </th>
                                    <th class="marks-cell">Наличие</th>
                                    <th class="marks-cell">
                                        {% include 'mainapp/components/_sort_header.html' with field='last_mark_date' label='Дата и время' current_sort=sort %}
                                    </th>
                                    <th class="actions-cell">Действия</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for source in sources %}
                                    {% with marks=source.marks.all %}
                                    {% if marks %}
                                        <!-- Первая строка с информацией об объекте и первой отметкой -->
                                        <tr data-source-id="{{ source.id }}">
                                            <td class="source-info-cell" rowspan="{{ marks.count }}">
                                                <div><strong>ID:</strong> {{ source.id }}</div>
                                                <div><strong>Имя:</strong> {{ source.objitem_name }}</div>
                                            </td>
                                            <td class="param-cell" rowspan="{{ marks.count }}">{{ source.frequency }}</td>
                                            <td class="param-cell" rowspan="{{ marks.count }}">{{ source.freq_range }}</td>
                                            <td class="param-cell" rowspan="{{ marks.count }}">{{ source.polarization }}</td>
                                            <td class="param-cell" rowspan="{{ marks.count }}">{{ source.modulation }}</td>
                                            <td class="param-cell" rowspan="{{ marks.count }}">{{ source.bod_velocity }}</td>
                                            {% with first_mark=marks.0 %}
                                            <td class="marks-cell" data-mark-id="{{ first_mark.id }}">
                                                <span class="mark-status {% if first_mark.mark %}mark-present{% else %}mark-absent{% endif %}">
                                                    {% if first_mark.mark %}✓ Есть{% else %}✗ Нет{% endif %}
                                                </span>
                                                {% if first_mark.can_edit %}
                                                <button class="btn btn-sm btn-outline-secondary btn-edit-mark ms-2" 
                                                        onclick="toggleMark({{ first_mark.id }}, {{ first_mark.mark|yesno:'true,false' }})">
                                                    ✎
                                                </button>
                                                {% endif %}
                                            </td>
                                            <td class="marks-cell">
                                                <div>{{ first_mark.timestamp|date:"d.m.Y H:i" }}</div>
                                                <small class="text-muted">{{ first_mark.created_by|default:"—" }}</small>
                                            </td>
                                            <td class="actions-cell" rowspan="{{ marks.count }}">
                                                <div class="action-buttons" id="actions-{{ source.id }}">
                                                    <button class="btn btn-success btn-mark btn-sm" 
                                                            onclick="addMark({{ source.id }}, true)">
                                                        ✓ Есть
                                                    </button>
                                                    <button class="btn btn-danger btn-mark btn-sm" 
                                                            onclick="addMark({{ source.id }}, false)">
                                                        ✗ Нет
                                                    </button>
                                                </div>
                                            </td>
                                            {% endwith %}
                                        </tr>
                                        
                                        <!-- Остальные отметки -->
                                        {% for mark in marks|slice:"1:" %}
                                        <tr data-source-id="{{ source.id }}">
                                            <td class="marks-cell" data-mark-id="{{ mark.id }}">
                                                <span class="mark-status {% if mark.mark %}mark-present{% else %}mark-absent{% endif %}">
                                                    {% if mark.mark %}✓ Есть{% else %}✗ Нет{% endif %}
                                                </span>
                                                {% if mark.can_edit %}
                                                <button class="btn btn-sm btn-outline-secondary btn-edit-mark ms-2" 
                                                        onclick="toggleMark({{ mark.id }}, {{ mark.mark|yesno:'true,false' }})">
                                                    ✎
                                                </button>
                                                {% endif %}
                                            </td>
                                            <td class="marks-cell">
                                                <div>{{ mark.timestamp|date:"d.m.Y H:i" }}</div>
                                                <small class="text-muted">{{ mark.created_by|default:"—" }}</small>
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    {% else %}
                                        <!-- Объект без отметок -->
                                        <tr data-source-id="{{ source.id }}">
                                            <td class="source-info-cell">
                                                <div><strong>ID:</strong> {{ source.id }}</div>
                                                <div><strong>Имя:</strong> {{ source.objitem_name }}</div>
                                            </td>
                                            <td class="param-cell">{{ source.frequency }}</td>
                                            <td class="param-cell">{{ source.freq_range }}</td>
                                            <td class="param-cell">{{ source.polarization }}</td>
                                            <td class="param-cell">{{ source.modulation }}</td>
                                            <td class="param-cell">{{ source.bod_velocity }}</td>
                                            <td colspan="2" class="no-marks">Отметок нет</td>
                                            <td class="actions-cell">
                                                <div class="action-buttons" id="actions-{{ source.id }}">
                                                    <button class="btn btn-success btn-mark btn-sm" 
                                                            onclick="addMark({{ source.id }}, true)">
                                                        ✓ Есть
                                                    </button>
                                                    <button class="btn btn-danger btn-mark btn-sm" 
                                                            onclick="addMark({{ source.id }}, false)">
                                                        ✗ Нет
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    {% endif %}
                                    {% endwith %}
                                {% empty %}
                                <tr>
                                    <td colspan="9" class="text-center py-4">
                                        <p class="text-muted mb-0">Объекты не найдены для выбранного спутника</p>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% else %}
    <!-- No satellite selected message -->
    <div class="row">
        <div class="col-12">
            <div class="alert alert-info text-center">
                <h5>Пожалуйста, выберите спутник для просмотра объектов</h5>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- Offcanvas Filter Panel -->
<div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasFilters" aria-labelledby="offcanvasFiltersLabel">
    <div class="offcanvas-header">
        <h5 class="offcanvas-title" id="offcanvasFiltersLabel">Фильтры</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Закрыть"></button>
    </div>
    <div class="offcanvas-body">
        <form method="get" id="filter-form">
            <!-- Mark Status Filter -->
            <div class="mb-2">
                <label class="form-label">Статус отметок:</label>
                <select name="mark_status" class="form-select form-select-sm">
                    <option value="">Все</option>
                    <option value="with_marks" {% if filter_mark_status == 'with_marks' %}selected{% endif %}>С отметками</option>
                    <option value="without_marks" {% if filter_mark_status == 'without_marks' %}selected{% endif %}>Без отметок</option>
                </select>
            </div>

            <!-- Date Range Filters -->
            <div class="mb-2">
                <label class="form-label">Дата отметки от:</label>
                <input type="date" class="form-control form-control-sm" name="date_from" value="{{ filter_date_from }}">
            </div>

            <div class="mb-2">
                <label class="form-label">Дата отметки до:</label>
                <input type="date" class="form-control form-control-sm" name="date_to" value="{{ filter_date_to }}">
            </div>

            <!-- User Selection - Multi-select -->
            <div class="mb-2">
                <label class="form-label">Пользователь:</label>
                <div class="d-flex justify-content-between mb-1">
                    <button type="button" class="btn btn-sm btn-outline-secondary"
                        onclick="selectAllOptions('user_id', true)">Выбрать</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary"
                        onclick="selectAllOptions('user_id', false)">Снять</button>
                </div>
                <select name="user_id" class="form-select form-select-sm mb-2" multiple size="6">
                    {% for user in users %}
                    <option value="{{ user.id }}" {% if user.id in selected_users %}selected{% endif %}>
                        {{ user.user.username }}
                    </option>
                    {% endfor %}
                </select>
            </div>

            {# Сохраняем параметры сортировки, поиска и спутника при применении фильтров #}
            {% if selected_satellite_id %}
                <input type="hidden" name="satellite_id" value="{{ selected_satellite_id }}">
            {% endif %}
            {% if request.GET.sort %}
                <input type="hidden" name="sort" value="{{ request.GET.sort }}">
            {% endif %}
            {% if request.GET.search %}
                <input type="hidden" name="search" value="{{ request.GET.search }}">
            {% endif %}
            {% if request.GET.items_per_page %}
                <input type="hidden" name="items_per_page" value="{{ request.GET.items_per_page }}">
            {% endif %}

            <div class="d-grid gap-2 mt-3">
                <button type="submit" class="btn btn-primary btn-sm">
                    Применить
                </button>
                <a href="?{% if selected_satellite_id %}satellite_id={{ selected_satellite_id }}{% endif %}" class="btn btn-secondary btn-sm">
                    Сбросить
                </a>
            </div>
        </form>
    </div>
</div>

<script>
// Satellite selection
function selectSatellite() {
    const select = document.getElementById('satellite-select');
    const satelliteId = select.value;
    
    if (satelliteId) {
        const urlParams = new URLSearchParams(window.location.search);
        urlParams.set('satellite_id', satelliteId);
        
        // Reset page when changing satellite
        urlParams.delete('page');
        
        window.location.search = urlParams.toString();
    } else {
        // Clear all params if no satellite selected
        window.location.search = '';
    }
}

// Multi-select helper function
function selectAllOptions(selectName, select) {
    const selectElement = document.querySelector(`select[name="${selectName}"]`);
    if (selectElement) {
        for (let option of selectElement.options) {
            option.selected = select;
        }
    }
}

// Update filter counter badge when filters are active
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const filterCounter = document.getElementById('filterCounter');
    
    if (filterCounter) {
        // Count active filters (excluding pagination, sort, search, items_per_page, and satellite_id)
        const excludedParams = ['page', 'sort', 'search', 'items_per_page', 'satellite_id'];
        let activeFilters = 0;
        
        for (const [key, value] of urlParams.entries()) {
            if (!excludedParams.includes(key) && value) {
                activeFilters++;
            }
        }
        
        if (activeFilters > 0) {
            filterCounter.textContent = activeFilters;
            filterCounter.style.display = 'inline-block';
        } else {
            filterCounter.style.display = 'none';
        }
    }
});
</script>
{% endblock %}

{% block extra_js %}
<script>
function addMark(sourceId, mark) {
    // Отключить кнопки для этого объекта
    const buttons = document.querySelectorAll(`#actions-${sourceId} button`);
    buttons.forEach(btn => btn.disabled = true);
    
    fetch("{% url 'mainapp:add_object_mark' %}", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': '{{ csrf_token }}'
        },
        body: `source_id=${sourceId}&mark=${mark}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Перезагрузить страницу для обновления таблицы
            location.reload();
        } else {
            // Включить кнопки обратно
            buttons.forEach(btn => btn.disabled = false);
            alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        buttons.forEach(btn => btn.disabled = false);
        alert('Ошибка при добавлении наличие сигнала');
    });
}

function toggleMark(markId, currentValue) {
    const newValue = !currentValue;
    const cell = document.querySelector(`td[data-mark-id="${markId}"]`);
    const editBtn = cell.querySelector('.btn-edit-mark');
    
    // Отключить кнопку редактирования на время запроса
    if (editBtn) {
        editBtn.disabled = true;
    }
    
    fetch("{% url 'mainapp:update_object_mark' %}", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': '{{ csrf_token }}'
        },
        body: `mark_id=${markId}&mark=${newValue}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Обновить отображение наличие сигнала без перезагрузки страницы
            const statusSpan = cell.querySelector('.mark-status');
            
            if (data.mark.mark) {
                statusSpan.textContent = '✓ Есть';
                statusSpan.className = 'mark-status mark-present';
            } else {
                statusSpan.textContent = '✗ Нет';
                statusSpan.className = 'mark-status mark-absent';
            }
            
            // Обновить значение в onclick для следующего переключения
            if (editBtn) {
                editBtn.setAttribute('onclick', `toggleMark(${markId}, ${data.mark.mark})`);
                editBtn.disabled = false;
            }
            
            // Если больше нельзя редактировать, убрать кнопку
            if (!data.mark.can_edit && editBtn) {
                editBtn.remove();
            }
        } else {
            // Включить кнопку обратно при ошибке
            if (editBtn) {
                editBtn.disabled = false;
            }
            alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (editBtn) {
            editBtn.disabled = false;
        }
        alert('Ошибка при изменении наличие сигнала');
    });
}
</script>
{% endblock %}
