{% extends 'mainapp/base.html' %}
{% load permission_tags %}

{% block title %}Список транспондеров{% endblock %}

{% block extra_css %}
<style>
    .table-responsive tr.selected {
        background-color: #d4edff;
    }
    .sticky-top {
        position: sticky;
        top: 0;
        z-index: 10;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-3">
    <div class="row mb-3">
        <div class="col-12">
            <h2>Список транспондеров</h2>
        </div>
    </div>

    <!-- Toolbar -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center gap-3">
                        <!-- Search bar -->
                        <div style="min-width: 200px; flex-grow: 1; max-width: 400px;">
                            <div class="input-group">
                                <input type="text" id="toolbar-search" class="form-control" placeholder="Поиск..."
                                    value="{{ search_query|default:'' }}">
                                <button type="button" class="btn btn-outline-primary"
                                    onclick="performSearch()">Найти</button>
                                <button type="button" class="btn btn-outline-secondary"
                                    onclick="clearSearch()">Очистить</button>
                            </div>
                        </div>

                        <!-- Items per page select -->
                        <div>
                            <label for="items-per-page" class="form-label mb-0">Показать:</label>
                            <select name="items_per_page" id="items-per-page"
                                class="form-select form-select-sm d-inline-block" style="width: auto;"
                                onchange="updateItemsPerPage()">
                                {% for option in available_items_per_page %}
                                <option value="{{ option }}" {% if option == items_per_page %}selected{% endif %}>
                                    {{ option }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- Action buttons -->
                        <div class="d-flex gap-2">
                            {% if user|has_perm:'transponder_create' %}
                            <a href="{% url 'mainapp:transponder_create' %}" class="btn btn-success btn-sm" title="Создать">
                                <i class="bi bi-plus-circle"></i> Создать
                            </a>
                            {% endif %}
                            {% if user|has_perm:'transponder_import_xml' %}
                            <a href="{% url 'mainapp:add_trans' %}" class="btn btn-warning btn-sm" title="Загрузить из XML">
                                <i class="bi bi-upload"></i> Загрузить XML
                            </a>
                            {% endif %}
                            {% if user|has_perm:'transponder_delete' %}
                            <button type="button" class="btn btn-danger btn-sm" title="Удалить"
                                onclick="deleteSelectedTransponders()">
                                <i class="bi bi-trash"></i> Удалить
                            </button>
                            {% endif %}
                        </div>

                        <!-- Filter Toggle Button -->
                        <div>
                            <button class="btn btn-outline-primary btn-sm" type="button" data-bs-toggle="offcanvas" 
                                data-bs-target="#offcanvasFilters" aria-controls="offcanvasFilters">
                                <i class="bi bi-funnel"></i> Фильтры
                                <span id="filterCounter" class="badge bg-danger" style="display: none;">0</span>
                            </button>
                        </div>

                        <!-- Pagination -->
                        <div class="ms-auto">
                            {% include 'mainapp/components/_pagination.html' with page_obj=page_obj show_info=True %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </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">
                <!-- Satellite 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('satellite_id', true)">Выбрать</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary"
                            onclick="selectAllOptions('satellite_id', false)">Снять</button>
                    </div>
                    <select name="satellite_id" class="form-select form-select-sm mb-2" multiple size="6">
                        {% for satellite in satellites %}
                        <option value="{{ satellite.id }}" {% if satellite.id in selected_satellites %}selected{% endif %}>
                            {{ satellite.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Polarization 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('polarization', true)">Выбрать</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary"
                            onclick="selectAllOptions('polarization', false)">Снять</button>
                    </div>
                    <select name="polarization" class="form-select form-select-sm mb-2" multiple size="4">
                        {% for pol in polarizations %}
                        <option value="{{ pol.id }}" {% if pol.id in selected_polarizations %}selected{% endif %}>
                            {{ pol.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>

                <!-- Downlink Filter -->
                <div class="mb-2">
                    <label class="form-label">Downlink, МГц:</label>
                    <input type="number" step="0.001" name="downlink_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ downlink_min|default:'' }}">
                    <input type="number" step="0.001" name="downlink_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ downlink_max|default:'' }}">
                </div>

                <!-- Uplink Filter -->
                <div class="mb-2">
                    <label class="form-label">Uplink, МГц:</label>
                    <input type="number" step="0.001" name="uplink_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ uplink_min|default:'' }}">
                    <input type="number" step="0.001" name="uplink_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ uplink_max|default:'' }}">
                </div>

                <!-- Frequency Range Filter -->
                <div class="mb-2">
                    <label class="form-label">Полоса, МГц:</label>
                    <input type="number" step="0.001" name="freq_range_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ freq_range_min|default:'' }}">
                    <input type="number" step="0.001" name="freq_range_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ freq_range_max|default:'' }}">
                </div>

                <!-- SNR Filter -->
                <div class="mb-2">
                    <label class="form-label">ОСШ, дБ:</label>
                    <input type="number" step="0.1" name="snr_min" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ snr_min|default:'' }}">
                    <input type="number" step="0.1" name="snr_max" class="form-control form-control-sm"
                        placeholder="До" value="{{ snr_max|default:'' }}">
                </div>

                <!-- Date Filter -->
                <div class="mb-2">
                    <label class="form-label">Дата создания:</label>
                    <input type="date" name="date_from" id="date_from" class="form-control form-control-sm mb-1"
                        placeholder="От" value="{{ date_from|default:'' }}">
                    <input type="date" name="date_to" id="date_to" class="form-control form-control-sm"
                        placeholder="До" value="{{ date_to|default:'' }}">
                </div>

                <!-- Apply Filters and Reset Buttons -->
                <div class="d-grid gap-2 mt-2">
                    <button type="submit" class="btn btn-primary btn-sm">Применить</button>
                    <a href="?" class="btn btn-secondary btn-sm">Сбросить</a>
                </div>
            </form>
        </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" style="font-size: 0.85rem;">
                            <thead class="table-dark sticky-top">
                                <tr>
                                    <th scope="col" class="text-center" style="width: 3%;">
                                        <input type="checkbox" id="select-all" class="form-check-input">
                                    </th>
                                    <th scope="col" class="text-center" style="min-width: 60px;">
                                        <a href="javascript:void(0)" onclick="updateSort('id')" class="text-white text-decoration-none">
                                            ID
                                            {% if sort == 'id' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-id' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('name')" class="text-white text-decoration-none">
                                            Название
                                            {% if sort == 'name' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-name' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('sat_id__name')" class="text-white text-decoration-none">
                                            Спутник
                                            {% if sort == 'sat_id__name' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-sat_id__name' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 100px;">
                                        <a href="javascript:void(0)" onclick="updateSort('downlink')" class="text-white text-decoration-none">
                                            Downlink, МГц
                                            {% if sort == 'downlink' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-downlink' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 100px;">
                                        <a href="javascript:void(0)" onclick="updateSort('uplink')" class="text-white text-decoration-none">
                                            Uplink, МГц
                                            {% if sort == 'uplink' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-uplink' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 100px;">
                                        <a href="javascript:void(0)" onclick="updateSort('frequency_range')" class="text-white text-decoration-none">
                                            Полоса, МГц
                                            {% if sort == 'frequency_range' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-frequency_range' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 100px;">Перенос, МГц</th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('zone_name')" class="text-white text-decoration-none">
                                            Зона покрытия
                                            {% if sort == 'zone_name' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-zone_name' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 80px;">
                                        <a href="javascript:void(0)" onclick="updateSort('polarization__name')" class="text-white text-decoration-none">
                                            Поляризация
                                            {% if sort == 'polarization__name' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-polarization__name' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 80px;">
                                        <a href="javascript:void(0)" onclick="updateSort('snr')" class="text-white text-decoration-none">
                                            ОСШ, дБ
                                            {% if sort == 'snr' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-snr' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" class="text-center" style="min-width: 80px;">
                                        <a href="javascript:void(0)" onclick="updateSort('objitem_count')" class="text-white text-decoration-none">
                                            Кол-во точек
                                            {% if sort == 'objitem_count' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-objitem_count' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('created_at')" class="text-white text-decoration-none">
                                            Создано
                                            {% if sort == 'created_at' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-created_at' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" style="min-width: 120px;">
                                        <a href="javascript:void(0)" onclick="updateSort('updated_at')" class="text-white text-decoration-none">
                                            Обновлено
                                            {% if sort == 'updated_at' %}
                                                <i class="bi bi-arrow-up"></i>
                                            {% elif sort == '-updated_at' %}
                                                <i class="bi bi-arrow-down"></i>
                                            {% endif %}
                                        </a>
                                    </th>
                                    <th scope="col" class="text-center" style="min-width: 100px;">Действия</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for transponder in processed_transponders %}
                                <tr>
                                    <td class="text-center">
                                        <input type="checkbox" class="form-check-input item-checkbox"
                                            value="{{ transponder.id }}">
                                    </td>
                                    <td class="text-center">{{ transponder.id }}</td>
                                    <td>{{ transponder.name }}</td>
                                    <td>
                                        {% if transponder.satellite_id %}
                                        <a href="#" class="text-decoration-underline"
                                            onclick="showSatelliteModal({{ transponder.satellite_id }}); return false;">
                                            {{ transponder.satellite }}
                                        </a>
                                        {% else %}
                                        {{ transponder.satellite }}
                                        {% endif %}
                                    </td>
                                    <td>{{ transponder.downlink }}</td>
                                    <td>{{ transponder.uplink }}</td>
                                    <td>{{ transponder.frequency_range }}</td>
                                    <td>{{ transponder.transfer }}</td>
                                    <td>{{ transponder.zone_name }}</td>
                                    <td>{{ transponder.polarization }}</td>
                                    <td>{{ transponder.snr }}</td>
                                    <td class="text-center">{{ transponder.objitem_count }}</td>
                                    <td>{{ transponder.created_at|date:"d.m.Y H:i" }}</td>
                                    <td>{{ transponder.updated_at|date:"d.m.Y H:i" }}</td>
                                    <td class="text-center">
                                        {% if user|has_perm:'transponder_edit' %}
                                            <a href="{% url 'mainapp:transponder_update' transponder.id %}" 
                                               class="btn btn-sm btn-outline-warning"
                                               title="Редактировать транспондер">
                                                <i class="bi bi-pencil"></i>
                                            </a>
                                        {% else %}
                                            <button type="button" class="btn btn-sm btn-outline-secondary" disabled title="Недостаточно прав">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="15" class="text-center text-muted">Нет данных для отображения</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
let lastCheckedIndex = null;

function updateRowHighlight(checkbox) {
    const row = checkbox.closest('tr');
    if (checkbox.checked) {
        row.classList.add('selected');
    } else {
        row.classList.remove('selected');
    }
}

function handleCheckboxClick(e) {
    if (e.shiftKey && lastCheckedIndex !== null) {
        const checkboxes = document.querySelectorAll('.item-checkbox');
        const currentIndex = Array.from(checkboxes).indexOf(e.target);
        const startIndex = Math.min(lastCheckedIndex, currentIndex);
        const endIndex = Math.max(lastCheckedIndex, currentIndex);

        for (let i = startIndex; i <= endIndex; i++) {
            checkboxes[i].checked = e.target.checked;
            updateRowHighlight(checkboxes[i]);
        }
    } else {
        updateRowHighlight(e.target);
    }
    lastCheckedIndex = Array.from(document.querySelectorAll('.item-checkbox')).indexOf(e.target);
}

// Function to delete selected transponders
function deleteSelectedTransponders() {
    const checkedCheckboxes = document.querySelectorAll('.item-checkbox:checked');

    if (checkedCheckboxes.length === 0) {
        alert('Пожалуйста, выберите хотя бы один транспондер для удаления');
        return;
    }

    const selectedIds = [];
    checkedCheckboxes.forEach(checkbox => {
        selectedIds.push(checkbox.value);
    });

    const url = '{% url "mainapp:delete_selected_transponders" %}' + '?ids=' + selectedIds.join(',');
    window.location.href = url;
}

// Search functionality
function performSearch() {
    const searchValue = document.getElementById('toolbar-search').value.trim();
    const urlParams = new URLSearchParams(window.location.search);
    
    if (searchValue) {
        urlParams.set('search', searchValue);
    } else {
        urlParams.delete('search');
    }
    
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

function clearSearch() {
    document.getElementById('toolbar-search').value = '';
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.delete('search');
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

document.getElementById('toolbar-search').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        performSearch();
    }
});

// Items per page functionality
function updateItemsPerPage() {
    const itemsPerPage = document.getElementById('items-per-page').value;
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('items_per_page', itemsPerPage);
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

// Sorting functionality
function updateSort(field) {
    const urlParams = new URLSearchParams(window.location.search);
    const currentSort = urlParams.get('sort');
    
    let newSort;
    if (currentSort === field) {
        newSort = '-' + field;
    } else if (currentSort === '-' + field) {
        newSort = field;
    } else {
        newSort = field;
    }
    
    urlParams.set('sort', newSort);
    urlParams.delete('page');
    window.location.search = urlParams.toString();
}

// Function to select/deselect all options in a select element
function selectAllOptions(selectName, selectAll) {
    const selectElement = document.querySelector(`select[name="${selectName}"]`);
    if (selectElement) {
        for (let i = 0; i < selectElement.options.length; i++) {
            selectElement.options[i].selected = selectAll;
        }
    }
}

// Filter counter functionality
function updateFilterCounter() {
    const form = document.getElementById('filter-form');
    const formData = new FormData(form);
    let filterCount = 0;

    for (const [key, value] of formData.entries()) {
        if (value && value.trim() !== '') {
            if (key === 'satellite_id' || key === 'polarization') {
                continue;
            }
            filterCount++;
        }
    }
    
    // Count selected options in multi-select fields
    const satelliteSelect = document.querySelector('select[name="satellite_id"]');
    if (satelliteSelect) {
        const selectedOptions = Array.from(satelliteSelect.selectedOptions).filter(opt => opt.selected);
        if (selectedOptions.length > 0) {
            filterCount++;
        }
    }
    
    const polarizationSelect = document.querySelector('select[name="polarization"]');
    if (polarizationSelect) {
        const selectedOptions = Array.from(polarizationSelect.selectedOptions).filter(opt => opt.selected);
        if (selectedOptions.length > 0) {
            filterCount++;
        }
    }

    const counterElement = document.getElementById('filterCounter');
    if (counterElement) {
        if (filterCount > 0) {
            counterElement.textContent = filterCount;
            counterElement.style.display = 'inline';
        } else {
            counterElement.style.display = 'none';
        }
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    const selectAllCheckbox = document.getElementById('select-all');
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');

    if (selectAllCheckbox && itemCheckboxes.length > 0) {
        selectAllCheckbox.addEventListener('change', function () {
            itemCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
                updateRowHighlight(checkbox);
            });
        });

        itemCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                selectAllCheckbox.checked = allChecked;
            });
            
            checkbox.addEventListener('click', handleCheckboxClick);
        });
    }

    updateFilterCounter();

    const form = document.getElementById('filter-form');
    if (form) {
        const inputFields = form.querySelectorAll('input[type="text"], input[type="number"], input[type="date"]');
        inputFields.forEach(input => {
            input.addEventListener('input', updateFilterCounter);
            input.addEventListener('change', updateFilterCounter);
        });

        const selectFields = form.querySelectorAll('select');
        selectFields.forEach(select => {
            select.addEventListener('change', updateFilterCounter);
        });
    }

    const offcanvasElement = document.getElementById('offcanvasFilters');
    if (offcanvasElement) {
        offcanvasElement.addEventListener('show.bs.offcanvas', updateFilterCounter);
    }
});
</script>

<!-- Include the satellite modal component -->
{% include 'mainapp/components/_satellite_modal.html' %}

{% endblock %}
