{% 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>
    .satellite-selector {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .nav-tabs .nav-link.active {
        background-color: #0d6efd;
        color: white;
        border-color: #0d6efd;
    }
    
    /* Стили для ячеек истории */
    .mark-cell {
        text-align: center;
        padding: 4px 6px;
        font-size: 0.8rem;
        min-width: 70px;
    }
    
    .mark-present {
        background-color: #d4edda !important;
        color: #155724;
    }
    
    .mark-absent {
        background-color: #f8d7da !important;
        color: #721c24;
    }
    
    .mark-empty {
        background-color: #f8f9fa;
        color: #adb5bd;
    }
    
    .mark-user {
        font-size: 0.7rem;
        color: #6c757d;
        display: block;
    }
    
    /* Стили для кнопок отметок */
    .mark-btn-group {
        display: flex;
        gap: 4px;
        justify-content: center;
    }
    
    .mark-btn {
        padding: 2px 10px;
        font-size: 0.8rem;
        border-radius: 4px;
        cursor: pointer;
        border: 2px solid transparent;
    }
    
    .mark-btn-yes {
        background-color: #e8f5e9;
        color: #2e7d32;
        border-color: #a5d6a7;
    }
    
    .mark-btn-yes.selected {
        background-color: #4caf50;
        color: white;
    }
    
    .mark-btn-no {
        background-color: #ffebee;
        color: #c62828;
        border-color: #ef9a9a;
    }
    
    .mark-btn-no.selected {
        background-color: #f44336;
        color: white;
    }
    
    .filter-panel {
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        padding: 1rem;
        margin-bottom: 1rem;
    }
    
    /* Таблица истории */
    .history-table {
        font-size: 0.85rem;
    }
    
    .history-table th {
        position: sticky;
        top: 0;
        background: #343a40;
        color: white;
        font-weight: 500;
        white-space: nowrap;
        padding: 6px 8px;
        font-size: 0.75rem;
    }
    
    .history-table td {
        padding: 4px 6px;
        vertical-align: middle;
    }
    
    .history-table .name-col {
        position: sticky;
        left: 0;
        background: #f8f9fa;
        min-width: 250px;
        white-space: normal;
        word-break: break-word;
    }
    
    .history-table thead .name-col {
        background: #343a40;
        z-index: 10;
    }
    
    .history-wrapper {
        max-height: 65vh;
        overflow: auto;
    }
</style>
{% endblock %}

{% block content %}
<div class="{% if full_width_page %}container-fluid{% else %}container{% endif %} px-3">
    <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 %}
    <!-- Tabs -->
    <ul class="nav nav-tabs" id="marksTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="entry-tab" data-bs-toggle="tab" data-bs-target="#entry-pane" 
                    type="button" role="tab">
                <i class="bi bi-pencil-square"></i> Проставить отметки
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history-pane" 
                    type="button" role="tab">
                <i class="bi bi-clock-history"></i> История отметок
            </button>
        </li>
    </ul>

    <div class="tab-content" id="marksTabsContent">
        <!-- Entry Tab -->
        <div class="tab-pane fade show active" id="entry-pane" role="tabpanel">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div>
                        <input type="text" id="entry-search" class="form-control form-control-sm" 
                               placeholder="Поиск по имени..." style="width: 200px;">
                    </div>
                    <div class="d-flex gap-2">
                        {% if user|has_perm:'tech_analyze_create' %}
                        <button class="btn btn-outline-primary btn-sm" onclick="openCreateModal()">
                            <i class="bi bi-plus-lg"></i> Создать теханализ
                        </button>
                        {% endif %}
                        {% if user|has_perm:'mark_create' %}
                        <button class="btn btn-success" id="save-marks-btn" onclick="saveMarks()" disabled>
                            <i class="bi bi-check-lg"></i> Сохранить 
                            <span class="badge bg-light text-dark" id="marks-count">0</span>
                        </button>
                        {% endif %}
                    </div>
                </div>
                <div class="card-body p-0">
                    <div id="entry-table"></div>
                </div>
            </div>
        </div>

        <!-- History Tab -->
        <div class="tab-pane fade" id="history-pane" role="tabpanel">
            <div class="filter-panel">
                <div class="row align-items-end">
                    <div class="col-md-2">
                        <label class="form-label">Дата от:</label>
                        <input type="date" id="history-date-from" class="form-control form-control-sm">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Дата до:</label>
                        <input type="date" id="history-date-to" class="form-control form-control-sm">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Показывать:</label>
                        <select id="history-page-size" class="form-select form-select-sm">
                            <option value="0" selected>Все</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                            <option value="200">200</option>
                            <option value="500">500</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Поиск по имени:</label>
                        <input type="text" id="history-search" class="form-control form-control-sm" 
                               placeholder="Введите имя..." oninput="filterHistoryTable()">
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-primary btn-sm" onclick="loadHistory()">
                            Показать
                        </button>
                        <button class="btn btn-secondary btn-sm" onclick="resetHistoryFilters()">
                            Сбросить
                        </button>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-body p-0">
                    <div class="history-wrapper" id="history-container">
                        <div class="text-center p-4 text-muted">
                            Нажмите "Показать" для загрузки данных
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% else %}
    <div class="alert alert-info text-center">
        <h5> Пожалуйста, выберите спутник</h5>
    </div>
    {% endif %}
</div>

{% if user|has_perm:'tech_analyze_create' %}
<!-- Modal for creating TechAnalyze -->
<div class="modal fade" id="createTechAnalyzeModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle"></i> Создать теханализ</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="create-tech-analyze-form">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Имя <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="ta-name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Частота, МГц</label>
                            <input type="number" step="0.001" class="form-control" id="ta-frequency">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Полоса, МГц</label>
                            <input type="number" step="0.001" class="form-control" id="ta-freq-range">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Сим. скорость</label>
                            <input type="number" class="form-control" id="ta-bod-velocity">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Поляризация</label>
                            <select class="form-select" id="ta-polarization">
                                <option value="">-- Выберите --</option>
                                {% for p in polarizations %}
                                <option value="{{ p.name }}">{{ p.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Модуляция</label>
                            <select class="form-select" id="ta-modulation">
                            <option value="">-- Выберите --</option>
                                {% for m in modulations %}
                                <option value="{{ m.name }}">{{ m.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Стандарт</label>
                            <select class="form-select" id="ta-standard">
                                <option value="">-- Выберите --</option>
                                {% for s in standards %}
                                <option value="{{ s.name }}">{{ s.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    {% if user|has_perm:'mark_create' %}
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="ta-add-mark" checked>
                        <label class="form-check-label" for="ta-add-mark">
                            Сразу добавить отметку "Есть сигнал"
                        </label>
                    </div>
                    {% endif %}
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                <button type="button" class="btn btn-primary" onclick="createTechAnalyze()">Создать</button>
            </div>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_js %}
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
<script>
const SATELLITE_ID = {% if selected_satellite_id %}{{ selected_satellite_id }}{% else %}null{% endif %};
const CSRF_TOKEN = '{{ csrf_token }}';
const CAN_CREATE_MARK = {% if user|has_perm:'mark_create' %}true{% else %}false{% endif %};
const CAN_CREATE_TECH_ANALYZE = {% if user|has_perm:'tech_analyze_create' %}true{% else %}false{% endif %};

let entryTable = null;
let pendingMarks = {};

function selectSatellite() {
    const select = document.getElementById('satellite-select');
    if (select.value) {
        window.location.search = `satellite_id=${select.value}`;
    } else {
        window.location.search = '';
    }
}

// Entry table
function initEntryTable() {
    if (!SATELLITE_ID) return;
    
    // Базовые колонки
    const columns = [
        {title: "ID", field: "id", width: 60},
        {title: "Имя", field: "name", width: 500},
        {title: "Частота", field: "frequency", width: 120, hozAlign: "right",
            formatter: c => c.getValue() ? c.getValue().toFixed(3) : '-'},
        {title: "Полоса", field: "freq_range", width: 120, hozAlign: "right",
            formatter: c => c.getValue() ? c.getValue().toFixed(3) : '-'},
        {title: "Сим.v", field: "bod_velocity", width: 120, hozAlign: "right",
            formatter: c => c.getValue() ? Math.round(c.getValue()) : '-'},
        {title: "Пол.", field: "polarization", width: 105, hozAlign: "center"},
        {title: "Мод.", field: "modulation", width: 95, hozAlign: "center"},
        {title: "Станд.", field: "standard", width: 125},
        {title: "Посл. отметка", field: "last_mark", width: 190,
            formatter: function(c) {
                const d = c.getValue();
                if (!d) return '<span class="text-muted">—</span>';
                const icon = d.mark ? '✓' : '✗';
                const cls = d.mark ? 'text-success' : 'text-danger';
                return `<span class="${cls}">${icon}</span> ${d.timestamp}`;
            }
        },
    ];
    
    // Добавляем колонку отметок только если есть право
    if (CAN_CREATE_MARK) {
        columns.push({
            title: "Отметка", field: "id", width: 100, hozAlign: "center", headerSort: false,
            formatter: function(c) {
                const row = c.getRow().getData();
                const id = row.id;
                if (!row.can_add_mark) return '<span class="text-muted small">5 мин</span>';
                const yesS = pendingMarks[id] === true ? 'selected' : '';
                const noS = pendingMarks[id] === false ? 'selected' : '';
                return `<div class="mark-btn-group">
                    <button type="button" class="mark-btn mark-btn-yes ${yesS}" data-id="${id}" data-val="true">✓</button>
                    <button type="button" class="mark-btn mark-btn-no ${noS}" data-id="${id}" data-val="false">✗</button>
                </div>`;
            }
        });
    }
    
    entryTable = new Tabulator("#entry-table", {
        ajaxURL: "{% url 'mainapp:signal_marks_entry_api' %}",
        ajaxParams: { satellite_id: SATELLITE_ID },
        pagination: true,
        paginationMode: "remote",
        paginationSize: 100,
        paginationSizeSelector: [50, 100, 200, 500, true],
        layout: "fitColumns",
        height: "65vh",
        placeholder: "Нет данных",
        columns: columns,
    });
    
    // Делегирование событий для кнопок отметок - без перерисовки таблицы
    document.getElementById('entry-table').addEventListener('click', function(e) {
        const btn = e.target.closest('.mark-btn');
        if (!btn) return;
        
        e.preventDefault();
        e.stopPropagation();
        
        const id = parseInt(btn.dataset.id);
        const val = btn.dataset.val === 'true';
        
        // Переключаем отметку
        if (pendingMarks[id] === val) {
            delete pendingMarks[id];
        } else {
            pendingMarks[id] = val;
        }
        
        // Обновляем только кнопки в этой строке
        const container = btn.closest('.mark-btn-group');
        if (container) {
            const yesBtn = container.querySelector('.mark-btn-yes');
            const noBtn = container.querySelector('.mark-btn-no');
            
            yesBtn.classList.toggle('selected', pendingMarks[id] === true);
            noBtn.classList.toggle('selected', pendingMarks[id] === false);
        }
        
        updateMarksCount();
    });
}

function updateMarksCount() {
    const count = Object.keys(pendingMarks).length;
    document.getElementById('marks-count').textContent = count;
    document.getElementById('save-marks-btn').disabled = count === 0;
}

function saveMarks() {
    const marks = Object.entries(pendingMarks).map(([id, mark]) => ({
        tech_analyze_id: parseInt(id), mark: mark
    }));
    if (!marks.length) return;
    
    const btn = document.getElementById('save-marks-btn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Сохранение...';
    
    fetch("{% url 'mainapp:save_signal_marks' %}", {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'X-CSRFToken': CSRF_TOKEN},
        body: JSON.stringify({ marks })
    })
    .then(r => r.json())
    .then(data => {
        // Восстанавливаем кнопку сначала
        btn.innerHTML = '<i class="bi bi-check-lg"></i> Сохранить <span class="badge bg-light text-dark" id="marks-count">0</span>';
        
        if (data.success) {
            pendingMarks = {};
            updateMarksCount();
            // Перезагружаем данные таблицы
            if (entryTable) {
                entryTable.setData("{% url 'mainapp:signal_marks_entry_api' %}", { satellite_id: SATELLITE_ID });
            }
            alert(`Сохранено: ${data.created}` + (data.skipped ? `, пропущено: ${data.skipped}` : ''));
        } else {
            updateMarksCount();
            alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
        }
    })
    .catch(e => {
        console.error('Save error:', e);
        btn.innerHTML = '<i class="bi bi-check-lg"></i> Сохранить <span class="badge bg-light text-dark" id="marks-count">0</span>';
        updateMarksCount();
        alert('Ошибка сохранения: ' + e.message);
    });
}

// History
function loadHistory() {
    const dateFrom = document.getElementById('history-date-from').value;
    const dateTo = document.getElementById('history-date-to').value;
    const pageSize = document.getElementById('history-page-size').value;
    const container = document.getElementById('history-container');
    
    container.innerHTML = '<div class="text-center p-4"><span class="spinner-border"></span></div>';
    
    let url = `{% url 'mainapp:signal_marks_history_api' %}?satellite_id=${SATELLITE_ID}`;
    if (dateFrom) url += `&date_from=${dateFrom}`;
    if (dateTo) url += `&date_to=${dateTo}`;
    // size=0 означает "все записи"
    url += `&size=${pageSize || 0}`;
    
    fetch(url)
        .then(r => r.json())
        .then(data => {
            if (data.error) {
                container.innerHTML = `<div class="alert alert-danger m-3">${data.error}</div>`;
                return;
            }
            if (data.message) {
                container.innerHTML = `<div class="alert alert-info m-3">${data.message}</div>`;
                return;
            }
            
            // Build HTML table
            let html = '<table class="table table-bordered table-sm history-table mb-0">';
            html += '<thead><tr>';
            html += '<th class="name-col">Имя</th>';
            
            for (const period of data.periods) {
                html += `<th class="mark-cell">${period}</th>`;
            }
            html += '</tr></thead><tbody>';
            
            for (const row of data.data) {
                html += '<tr>';
                html += `<td class="name-col">${row.name}</td>`;
                
                for (const mark of row.marks) {
                    if (mark) {
                        const cls = mark.mark ? 'mark-present' : 'mark-absent';
                        const icon = mark.mark ? '✓' : '✗';
                        html += `<td class="mark-cell ${cls}">
                            <strong>${icon}</strong>
                            <span class="mark-user">${mark.user}</span>
                            <span class="mark-user">${mark.time}</span>
                        </td>`;
                    } else {
                        html += '<td class="mark-cell mark-empty">—</td>';
                    }
                }
                html += '</tr>';
            }
            
            html += '</tbody></table>';
            container.innerHTML = html;
        })
        .catch(e => {
            container.innerHTML = '<div class="alert alert-danger m-3">Ошибка загрузки</div>';
        });
}

function resetHistoryFilters() {
    document.getElementById('history-date-from').value = '';
    document.getElementById('history-date-to').value = '';
    document.getElementById('history-page-size').value = '0';
    document.getElementById('history-search').value = '';
    loadHistory();
}

function filterHistoryTable() {
    const searchValue = document.getElementById('history-search').value.toLowerCase().trim();
    const table = document.querySelector('.history-table');
    if (!table) return;
    
    const rows = table.querySelectorAll('tbody tr');
    rows.forEach(row => {
        const nameCell = row.querySelector('.name-col');
        if (nameCell) {
            const name = nameCell.textContent.toLowerCase();
            row.style.display = name.includes(searchValue) ? '' : 'none';
        }
    });
}

// Init
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('entry-search');
    if (searchInput) {
        let timeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                if (entryTable) {
                    entryTable.setData("{% url 'mainapp:signal_marks_entry_api' %}", {
                        satellite_id: SATELLITE_ID, search: this.value
                    });
                }
            }, 300);
        });
    }
    
    initEntryTable();
    
    document.getElementById('history-tab').addEventListener('shown.bs.tab', function() {
        loadHistory();
    });
});

// Modal
function openCreateModal() {
    if (!CAN_CREATE_TECH_ANALYZE) {
        alert('У вас нет прав для создания теханализа');
        return;
    }
    document.getElementById('create-tech-analyze-form').reset();
    const addMarkCheckbox = document.getElementById('ta-add-mark');
    if (addMarkCheckbox) addMarkCheckbox.checked = true;
    new bootstrap.Modal(document.getElementById('createTechAnalyzeModal')).show();
}

function createTechAnalyze() {
    if (!CAN_CREATE_TECH_ANALYZE) {
        alert('У вас нет прав для создания теханализа');
        return;
    }
    const name = document.getElementById('ta-name').value.trim();
    if (!name) { alert('Укажите имя'); return; }
    
    fetch("{% url 'mainapp:create_tech_analyze_for_marks' %}", {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'X-CSRFToken': CSRF_TOKEN},
        body: JSON.stringify({
            satellite_id: SATELLITE_ID,
            name: name,
            frequency: document.getElementById('ta-frequency').value,
            freq_range: document.getElementById('ta-freq-range').value,
            bod_velocity: document.getElementById('ta-bod-velocity').value,
            polarization: document.getElementById('ta-polarization').value,
            modulation: document.getElementById('ta-modulation').value,
            standard: document.getElementById('ta-standard').value,
        })
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            bootstrap.Modal.getInstance(document.getElementById('createTechAnalyzeModal')).hide();
            const addMarkCheckbox = document.getElementById('ta-add-mark');
            if (CAN_CREATE_MARK && addMarkCheckbox && addMarkCheckbox.checked) {
                pendingMarks[result.tech_analyze.id] = true;
                updateMarksCount();
            }
            entryTable.setData();
        } else {
            alert('Ошибка: ' + (result.error || 'Неизвестная ошибка'));
        }
    })
    .catch(e => alert('Ошибка создания'));
}
</script>
{% endblock %}
