{% extends 'admin/base.html' %}

{% block title %}Support Tickets{% endblock %}

{% block content %}
<div class="page-header">
    <div>
        <h1 class="page-title">Support Tickets</h1>
        <p class="page-subtitle">Manage and respond to support tickets from companies.</p>
    </div>
</div>

{% if tickets %}
<div class="card">
    <div class="card-body">
        <div class="filters-toolbar">
            <div class="filter-input">
                <label for="filterTitle">Title</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-magnifying-glass"></i>
                    <input type="text" id="filterTitle" placeholder="Search title">
                </div>
            </div>
            <div class="filter-input">
                <label for="filterCompany">Company</label>
                <div class="input-wrapper">
                    <i class="fa-light fa-building"></i>
                    <input type="text" id="filterCompany" placeholder="Search company">
                </div>
            </div>
            <div class="filter-input">
                <label for="filterPriority">Priority</label>
                <div class="input-wrapper input-select">
                    <i class="fa-light fa-filter"></i>
                    <select id="filterPriority">
                        <option value="all">All priorities</option>
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                        <option value="urgent">Urgent</option>
                    </select>
                </div>
            </div>
            <div class="filter-input">
                <label for="filterStatus">Status</label>
                <div class="input-wrapper input-select">
                    <i class="fa-light fa-signal-bars"></i>
                    <select id="filterStatus">
                        <option value="all">All statuses</option>
                        <option value="open">Open</option>
                        <option value="in_progress">In Progress</option>
                        <option value="resolved">Resolved</option>
                        <option value="closed">Closed</option>
                    </select>
                </div>
            </div>
            <div class="filter-action">
                <button id="refreshTickets" class="btn btn-secondary">
                    <i class="fa-light fa-rotate"></i>
                    <span>Refresh</span>
                </button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table" id="tickets-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Company</th>
                        <th>Priority</th>
                        <th>Status</th>
                        <th>Created</th>
                        <th>Updated</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {% for ticket in tickets %}
                    <tr>
                        <td data-title><strong>{{ ticket[1] }}</strong></td>
                        <td data-company>
                            <div>{{ ticket[7] }}</div>
                            <small style="color: #94a3b8;">{{ ticket[8] }}</small>
                        </td>
                        <td data-priority="{{ ticket[3] }}">
                            <span class="status status-{{ ticket[3] }}">{{ ticket[3]|title }}</span>
                        </td>
                        <td data-status="{{ ticket[4] }}">
                            <span class="status status-{{ ticket[4]|replace('_', '-') }}">{{ ticket[4]|replace('_', ' ')|title }}</span>
                        </td>
                        <td data-created-date="{{ ticket[5].isoformat() if ticket[5] else '' }}">{{ ticket[5].strftime('%Y-%m-%d %H:%M') if ticket[5] else '—' }}</td>
                        <td data-updated-date="{{ ticket[6].isoformat() if ticket[6] else '' }}">{{ ticket[6].strftime('%Y-%m-%d %H:%M') if ticket[6] else '—' }}</td>
                        <td>
                            <a href="{{ url_for('admin.view_support_ticket', ticket_id=ticket[0]) }}" class="btn btn-sm btn-primary view-link" style="position: relative; display: inline-block;">
                                View
                                {% if ticket[9] and ticket[9] > 0 %}
                                <span class="unread-badge">{{ ticket[9] if ticket[9] <= 99 else '99+' }}</span>
                                {% endif %}
                            </a>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <div class="table-footer" style="display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; background: #f8fafc; border-top: 1px solid #e2e8f0;">
            <div class="pagination-info" id="tickets-count"></div>
            <div class="pagination-controls" style="display: flex; align-items: center; gap: 12px;">
                <button type="button" class="pagination-button" id="tickets-prev">Previous</button>
                <span class="pagination-info" id="tickets-page-label">Page 1</span>
                <button type="button" class="pagination-button" id="tickets-next">Next</button>
            </div>
        </div>
    </div>
</div>
{% else %}
<div class="card">
    <div class="card-body">
        <div class="empty-state">
            <i class="fa-light fa-ticket"></i>
            <p>No support tickets yet.</p>
        </div>
    </div>
</div>
{% endif %}
{% endblock %}

{% block extra_css %}
<style>
    .status-low { background: rgba(148, 163, 184, 0.16); color: #64748b; }
    .status-medium { background: rgba(59, 130, 246, 0.16); color: #2563eb; }
    .status-high { background: rgba(245, 158, 11, 0.16); color: #d97706; }
    .status-urgent { background: rgba(239, 68, 68, 0.16); color: #dc2626; }
    .status-open { background: rgba(34, 197, 94, 0.16); color: #15803d; }
    .status-in-progress { background: rgba(14, 165, 233, 0.16); color: #0369a1; }
    .status-resolved { background: rgba(168, 85, 247, 0.16); color: #7c3aed; }
    .status-closed { background: rgba(148, 163, 184, 0.16); color: #64748b; }

    .unread-badge {
        position: absolute;
        top: -6px;
        right: -6px;
        background: #ef4444;
        color: white;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 11px;
        font-weight: 600;
        border: 2px solid white;
    }

    .view-link {
        position: relative;
    }

    .filters-toolbar {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 16px;
        padding: 16px 20px;
        background: #f8fafc;
        border-radius: 16px;
        border: 1px solid rgba(148, 163, 184, 0.18);
        margin-bottom: 20px;
    }

    .filters-toolbar .filter-input {
        display: flex;
        flex-direction: column;
        gap: 6px;
    }

    .filters-toolbar .filter-input label {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
        font-weight: 600;
    }

    .filters-toolbar .input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        padding: 10px 12px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .filters-toolbar .input-wrapper:focus-within {
        border-color: #2563eb;
        box-shadow: 0 12px 26px rgba(37, 99, 235, 0.18);
    }

    .filters-toolbar .input-wrapper i {
        margin-right: 10px;
        color: #94a3b8;
        font-size: 16px;
    }

    .filters-toolbar .input-wrapper input,
    .filters-toolbar .input-wrapper select {
        flex: 1;
        border: none;
        background: transparent;
        outline: none;
        font-size: 14px;
        color: #0f172a;
    }

    .filters-toolbar .input-wrapper select {
        appearance: none;
        padding-right: 18px;
        cursor: pointer;
    }

    .filters-toolbar .input-wrapper.input-select {
        position: relative;
    }

    .filters-toolbar .input-wrapper.input-select::after {
        content: '▼';
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        color: #94a3b8;
        font-size: 10px;
        pointer-events: none;
    }

    .filters-toolbar .filter-action {
        display: flex;
        align-items: flex-end;
    }

    .pagination-button {
        padding: 8px 16px;
        border: 1px solid #dbe3ee;
        border-radius: 8px;
        background: #ffffff;
        color: #0f172a;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .pagination-button:hover:not(:disabled) {
        border-color: rgba(37, 99, 235, 0.35);
        color: #2563eb;
    }

    .pagination-button:disabled {
        opacity: 0.45;
        cursor: not-allowed;
    }

    .pagination-info {
        font-size: 14px;
        color: #64748b;
    }
</style>
{% endblock %}

{% block extra_js %}
{% if tickets %}
<script>
    (function() {
        const tableBody = document.querySelector('#tickets-table tbody');
        const filterTitleInput = document.getElementById('filterTitle');
        const filterCompanyInput = document.getElementById('filterCompany');
        const filterPrioritySelect = document.getElementById('filterPriority');
        const filterStatusSelect = document.getElementById('filterStatus');
        const refreshButton = document.getElementById('refreshTickets');
        const prevBtn = document.getElementById('tickets-prev');
        const nextBtn = document.getElementById('tickets-next');
        const pageLabel = document.getElementById('tickets-page-label');
        const countLabel = document.getElementById('tickets-count');

        const rowsPerPage = 10;
        let currentPage = 1;

        const ticketRows = Array.from(document.querySelectorAll('#tickets-table tbody tr')).map(row => {
            const cells = row.querySelectorAll('td');
            return {
                row: row,
                title: (cells[0]?.textContent || '').trim().toLowerCase(),
                company: (cells[1]?.textContent || '').trim().toLowerCase(),
                priority: (cells[2]?.getAttribute('data-priority') || '').toLowerCase(),
                status: (cells[3]?.getAttribute('data-status') || '').toLowerCase(),
                created: cells[4]?.getAttribute('data-created-date') || '',
                updated: cells[5]?.getAttribute('data-updated-date') || ''
            };
        });

        function getFilteredTickets() {
            const titleSearch = (filterTitleInput.value || '').trim().toLowerCase();
            const companySearch = (filterCompanyInput.value || '').trim().toLowerCase();
            const priorityFilter = (filterPrioritySelect.value || 'all').toLowerCase();
            const statusFilter = (filterStatusSelect.value || 'all').toLowerCase();

            return ticketRows.filter(ticket => {
                if (titleSearch && !ticket.title.includes(titleSearch)) {
                    return false;
                }
                if (companySearch && !ticket.company.includes(companySearch)) {
                    return false;
                }
                if (priorityFilter !== 'all' && ticket.priority !== priorityFilter) {
                    return false;
                }
                if (statusFilter !== 'all' && ticket.status !== statusFilter) {
                    return false;
                }
                return true;
            });
        }

        function renderTable() {
            const filtered = getFilteredTickets();
            const totalPages = Math.max(1, Math.ceil(filtered.length / rowsPerPage));
            if (currentPage > totalPages) currentPage = totalPages;
            const start = (currentPage - 1) * rowsPerPage;
            const end = start + rowsPerPage;
            const pageItems = filtered.slice(start, end);

            // Hide all rows first
            ticketRows.forEach(t => t.row.style.display = 'none');
            
            // Show filtered rows
            pageItems.forEach(item => {
                item.row.style.display = '';
            });

            pageLabel.textContent = `Page ${currentPage} of ${totalPages}`;
            prevBtn.disabled = currentPage === 1;
            nextBtn.disabled = currentPage === totalPages;
            countLabel.textContent = `${filtered.length} ticket${filtered.length === 1 ? '' : 's'} found`;
        }

        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage -= 1;
                renderTable();
            }
        });

        nextBtn.addEventListener('click', () => {
            const filtered = getFilteredTickets();
            const totalPages = Math.max(1, Math.ceil(filtered.length / rowsPerPage));
            if (currentPage < totalPages) {
                currentPage += 1;
                renderTable();
            }
        });

        [filterTitleInput, filterCompanyInput, filterPrioritySelect, filterStatusSelect].forEach(input => {
            input.addEventListener('input', () => {
                currentPage = 1;
                renderTable();
            });
            input.addEventListener('change', () => {
                currentPage = 1;
                renderTable();
            });
        });

        refreshButton.addEventListener('click', () => window.location.reload());

        renderTable();
    })();
</script>
{% endif %}
{% endblock %}
