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

{% block title %}Тех. анализ - Список{% endblock %}

{% block extra_css %}
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
<style>
    .sticky-top {
        position: sticky;
        top: 0;
        z-index: 10;
    }
    #tech-analyze-table {
        font-size: 12px;
    }
    #tech-analyze-table .tabulator-header {
        font-size: 12px;
    }
    #tech-analyze-table .tabulator-cell {
        font-size: 12px;
        white-space: normal;
        word-wrap: break-word;
    }
    #tech-analyze-table .tabulator-row {
        min-height: 40px;
    }
</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="Поиск по ID или имени...">
                                <button type="button" class="btn btn-outline-primary" onclick="performSearch()">Найти</button>
                                <button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">Очистить</button>
                            </div>
                        </div>

                        <!-- Action buttons -->
                        <div class="d-flex gap-2">
                            {% if user|has_perm:'tech_analyze_create' %}
                            <a href="{% url 'mainapp:tech_analyze_entry' %}" class="btn btn-success btn-sm" title="Ввод данных">
                                <i class="bi bi-plus-circle"></i> Ввод данных
                            </a>
                            {% endif %}
                            {% if user|has_perm:'tech_analyze_delete' %}
                            <button type="button" class="btn btn-danger btn-sm" title="Удалить выбранные" onclick="deleteSelected()">
                                <i class="bi bi-trash"></i> Удалить
                            </button>
                            {% endif %}
                            {% if user|has_perm:'tech_analyze_edit' %}
                            <button type="button" class="btn btn-info btn-sm" title="Привязать к существующим точкам" onclick="showLinkModal()">
                                <i class="bi bi-link-45deg"></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>
                    </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>

                <!-- 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">
                    <div id="tech-analyze-table"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Link to Points Modal -->
<div class="modal fade" id="linkToPointsModal" tabindex="-1" aria-labelledby="linkToPointsModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="linkToPointsModalLabel">
                    <i class="bi bi-link-45deg"></i> Привязать к существующим точкам
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    <strong>Будут обновлены точки с отсутствующими данными:</strong>
                    <ul class="mb-0 mt-2">
                        <li>Модуляция (если "-")</li>
                        <li>Символьная скорость (если -1, 0 или пусто)</li>
                        <li>Стандарт (если "-")</li>
                        <li>Частота (если 0, -1 или пусто)</li>
                        <li>Полоса частот (если 0, -1 или пусто)</li>
                        <li>Поляризация (если "-")</li>
                        <li>Транспондер (если не привязан)</li>
                        <li>Источник LyngSat (если не привязан)</li>
                    </ul>
                </div>
                
                <div class="mb-3">
                    <label for="linkSatelliteSelect" class="form-label">Выберите спутник <span class="text-danger">*</span></label>
                    <select class="form-select" id="linkSatelliteSelect" required>
                        <option value="">Выберите спутник</option>
                        {% for satellite in satellites %}
                        <option value="{{ satellite.id }}">{{ satellite.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                
                <div id="linkResultMessage" class="alert" style="display: none;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
                <button type="button" class="btn btn-primary" id="confirmLinkBtn" onclick="confirmLink(event)">
                    <i class="bi bi-check-circle"></i> Привязать
                </button>
            </div>
        </div>
    </div>
</div>

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

{% endblock %}

{% block extra_js %}
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
<script>
// Helper function to get CSRF token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// Initialize Tabulator
const urlParams = new URLSearchParams(window.location.search);
const ajaxParams = {};
for (const [key, value] of urlParams.entries()) {
    if (ajaxParams[key]) {
        if (!Array.isArray(ajaxParams[key])) {
            ajaxParams[key] = [ajaxParams[key]];
        }
        ajaxParams[key].push(value);
    } else {
        ajaxParams[key] = value;
    }
}

const table = new Tabulator("#tech-analyze-table", {
    ajaxURL: "{% url 'mainapp:tech_analyze_api' %}",
    ajaxParams: ajaxParams,
    pagination: true,
    paginationMode: "remote",
    paginationSize: {{ items_per_page }},
    paginationSizeSelector: [25, 50, 100, 200, 500],
    layout: "fitDataStretch",
    height: "70vh",
    placeholder: "Нет данных для отображения",
    rowHeight: null, // Автоматическая высота строк
    columns: [
        {
            formatter: "rowSelection",
            titleFormatter: "rowSelection",
            hozAlign: "center",
            headerSort: false,
            width: 40,
            cellClick: function(e, cell) {
                cell.getRow().toggleSelect();
            }
        },
        {title: "ID", field: "id", width: 80, hozAlign: "center"},
        {
            title: "Имя", 
            field: "name", 
            minWidth: 250, 
            widthGrow: 3,
            formatter: function(cell) {
                return '<div style="white-space: normal; word-wrap: break-word; padding: 4px 0;">' + 
                       (cell.getValue() || '-') + '</div>';
            }
        },
        {
            title: "Спутник",
            field: "satellite_name",
            minWidth: 120,
            widthGrow: 1,
            formatter: function(cell) {
                const data = cell.getData();
                if (data.satellite_id) {
                    return '<a href="#" class="text-decoration-underline" onclick="showSatelliteModal(' + data.satellite_id + '); return false;">' + 
                           (data.satellite_name || '-') + '</a>';
                }
                return data.satellite_name || '-';
            }
        },
        {title: "Частота, МГц", field: "frequency", width: 120, hozAlign: "right", formatter: function(cell) {
            const val = cell.getValue();
            return val && val !== 0 ? val.toFixed(3) : '-';
        }},
        {title: "Полоса, МГц", field: "freq_range", width: 120, hozAlign: "right", formatter: function(cell) {
            const val = cell.getValue();
            return val && val !== 0 ? val.toFixed(3) : '-';
        }},
        {title: "Сим. скорость, БОД", field: "bod_velocity", width: 150, hozAlign: "right", formatter: function(cell) {
            const val = cell.getValue();
            return val && val !== 0 ? val.toFixed(0) : '-';
        }},
        {title: "Поляризация", field: "polarization_name", width: 120},
        {title: "Модуляция", field: "modulation_name", width: 120},
        {title: "Стандарт", field: "standard_name", width: 120},
        {
            title: "Примечание", 
            field: "note", 
            minWidth: 150, 
            widthGrow: 2,
            formatter: function(cell) {
                return '<div style="white-space: normal; word-wrap: break-word; padding: 4px 0;">' + 
                       (cell.getValue() || '-') + '</div>';
            }
        },
        {
            title: "Создано", 
            field: "created_at", 
            width: 140, 
            formatter: function(cell) {
                const val = cell.getValue();
                if (!val) return '-';
                try {
                    const date = new Date(val);
                    const day = String(date.getDate()).padStart(2, '0');
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const year = date.getFullYear();
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    return day + '.' + month + '.' + year + ' ' + hours + ':' + minutes;
                } catch (e) {
                    return '-';
                }
            }
        },
        {
            title: "Обновлено", 
            field: "updated_at", 
            width: 140, 
            formatter: function(cell) {
                const val = cell.getValue();
                if (!val) return '-';
                try {
                    const date = new Date(val);
                    const day = String(date.getDate()).padStart(2, '0');
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const year = date.getFullYear();
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    return day + '.' + month + '.' + year + ' ' + hours + ':' + minutes;
                } catch (e) {
                    return '-';
                }
            }
        },
    ],
});

// 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();
}

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

// 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');
    let filterCount = 0;

    // Count selected satellites
    const satelliteSelect = document.querySelector('select[name="satellite_id"]');
    if (satelliteSelect) {
        const selectedOptions = Array.from(satelliteSelect.selectedOptions).filter(function(opt) { return opt.selected; });
        if (selectedOptions.length > 0) {
            filterCount++;
        }
    }

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

// Delete selected items
function deleteSelected() {
    const selectedRows = table.getSelectedRows();

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

    if (!confirm('Удалить ' + selectedRows.length + ' записей?')) {
        return;
    }

    const selectedIds = selectedRows.map(function(row) { return row.getData().id; });

    fetch('{% url "mainapp:tech_analyze_delete" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            ids: selectedIds
        })
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.success) {
            table.replaceData();
        } else {
            alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
        }
    })
    .catch(function(error) {
        console.error('Error:', error);
        alert('Произошла ошибка при удалении записей');
    });
}

// Show link modal
function showLinkModal() {
    const modal = new bootstrap.Modal(document.getElementById('linkToPointsModal'));
    document.getElementById('linkResultMessage').style.display = 'none';
    modal.show();
}

// Confirm link
function confirmLink(event) {
    const satelliteId = document.getElementById('linkSatelliteSelect').value;
    const resultDiv = document.getElementById('linkResultMessage');
    
    if (!satelliteId) {
        resultDiv.className = 'alert alert-warning';
        resultDiv.textContent = 'Пожалуйста, выберите спутник';
        resultDiv.style.display = 'block';
        return;
    }
    
    // Show loading state
    const btn = document.getElementById('confirmLinkBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Обработка...';
    resultDiv.style.display = 'none';
    
    fetch('{% url "mainapp:tech_analyze_link_existing" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            satellite_id: satelliteId
        })
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.success) {
            resultDiv.className = 'alert alert-success';
            resultDiv.innerHTML = '<strong>Привязка завершена!</strong><br>' +
                'Обновлено точек: ' + data.updated + '<br>' +
                'Пропущено: ' + data.skipped + '<br>' +
                'Всего обработано: ' + data.total;
            
            if (data.errors && data.errors.length > 0) {
                resultDiv.innerHTML += '<br><br><strong>Ошибки:</strong><br>' + data.errors.join('<br>');
            }
        } else {
            resultDiv.className = 'alert alert-danger';
            resultDiv.textContent = 'Ошибка: ' + (data.error || 'Неизвестная ошибка');
        }
        resultDiv.style.display = 'block';
    })
    .catch(function(error) {
        console.error('Error:', error);
        resultDiv.className = 'alert alert-danger';
        resultDiv.textContent = 'Произошла ошибка при привязке точек';
        resultDiv.style.display = 'block';
    })
    .finally(function() {
        // Re-enable button
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-check-circle"></i> Привязать';
    });
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Update filter counter on page load
    updateFilterCounter();

    // Add event listeners to form elements to update counter when filters change
    const form = document.getElementById('filter-form');
    if (form) {
        const selectFields = form.querySelectorAll('select');
        selectFields.forEach(function(select) {
            select.addEventListener('change', updateFilterCounter);
        });
    }

    // Update counter when offcanvas is shown
    const offcanvasElement = document.getElementById('offcanvasFilters');
    if (offcanvasElement) {
        offcanvasElement.addEventListener('show.bs.offcanvas', updateFilterCounter);
    }
    
    // Set search value from URL
    const urlParams = new URLSearchParams(window.location.search);
    const searchQuery = urlParams.get('search');
    if (searchQuery) {
        document.getElementById('toolbar-search').value = searchQuery;
    }
});
</script>
{% endblock %}
