{% extends "layouts/base.html" %}

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

{% block extra_css %}
<style>
    .tickets-container {
        max-width: 1400px;
        margin: 0 auto;
        padding: 32px 24px 80px;
    }

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 24px;
        gap: 16px;
    }

    .page-header h2 {
        margin: 0 0 6px;
        font-size: 28px;
        font-weight: 700;
        color: #0f172a;
    }

    .page-header p {
        margin: 0;
        color: #475569;
        font-size: 15px;
    }

    .action-button {
        padding: 12px 24px;
        border-radius: 12px;
        border: none;
        background: #2563eb;
        color: #ffffff;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        box-shadow: 0 10px 24px rgba(37, 99, 235, 0.25);
    }

    .action-button:hover {
        background: #1d4ed8;
        box-shadow: 0 12px 28px rgba(37, 99, 235, 0.35);
        transform: translateY(-1px);
    }

    .table-card {
        background: #ffffff;
        border-radius: 16px;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
        overflow: hidden;
    }

    .table-responsive {
        overflow-x: auto;
    }

    .tickets-table {
        width: 100%;
        border-collapse: collapse;
    }

    .tickets-table thead {
        background: #f8fafc;
    }

    .tickets-table th {
        padding: 16px 20px;
        text-align: left;
        font-size: 12px;
        font-weight: 600;
        color: #64748b;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        border-bottom: 2px solid #e2e8f0;
    }

    .tickets-table tbody tr {
        border-bottom: 1px solid rgba(148, 163, 184, 0.12);
        transition: background 0.2s ease;
    }

    .tickets-table tbody tr:hover {
        background: #f8fafc;
    }

    .tickets-table tbody td {
        padding: 16px 20px;
        font-size: 14px;
        color: #0f172a;
    }

    .priority-badge,
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 999px;
        font-size: 12px;
        font-weight: 600;
        text-transform: capitalize;
    }

    .priority-low {
        background: rgba(148, 163, 184, 0.16);
        color: #64748b;
    }

    .priority-medium {
        background: rgba(59, 130, 246, 0.16);
        color: #2563eb;
    }

    .priority-high {
        background: rgba(245, 158, 11, 0.16);
        color: #d97706;
    }

    .priority-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;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #64748b;
    }

    .empty-state i {
        font-size: 48px;
        margin-bottom: 16px;
        color: #cbd5e1;
    }

    .empty-state p {
        font-size: 16px;
        margin: 0;
    }

    .view-link {
        color: #2563eb;
        text-decoration: none;
        font-weight: 600;
        transition: color 0.2s ease;
    }

    .view-link:hover {
        color: #1d4ed8;
        text-decoration: underline;
    }

    .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;
        display: inline-block;
    }

    .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;
    }

    .table-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 20px;
        background: #f8fafc;
        border-top: 1px solid #e2e8f0;
    }

    .pagination-controls {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .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;
    }

    /* Modal Styles */
    .modal {
        display: none;
        position: fixed;
        top: 26px;
        left: 23%;
        width: 100%;
        height: 100% !important;
        background: none;
        z-index: 1000;
        align-items: center;
        justify-content: center;
        padding: 24px;
        box-sizing: border-box;
        overflow-y: hidden;
    }

    .modal.active {
        display: flex;
    }

    .modal-content {
        background: white;
        padding: 32px;
        border-radius: 16px;
        max-width: 600px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
    }

    .modal-header h3 {
        margin: 0;
        font-size: 24px;
        font-weight: 700;
        color: #0f172a;
    }

    .close-modal {
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: #64748b;
        padding: 0;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        transition: all 0.2s ease;
    }

    .close-modal:hover {
        background: #f1f5f9;
        color: #0f172a;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        font-weight: 600;
        color: #0f172a;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
        width: 100%;
        padding: 12px 16px;
        border: 1px solid #dbe3ee;
        border-radius: 12px;
        font-size: 14px;
        color: #0f172a;
        transition: border 0.2s ease, box-shadow 0.2s ease;
        font-family: inherit;
    }

    .form-group input:focus,
    .form-group select:focus,
    .form-group textarea:focus {
        outline: none;
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
    }

    .form-group textarea {
        min-height: 120px;
        resize: vertical;
    }

    .form-actions {
        display: flex;
        gap: 12px;
        justify-content: flex-end;
        margin-top: 24px;
    }

    .btn-secondary {
        padding: 10px 20px;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        background: #ffffff;
        color: #0f172a;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .btn-secondary:hover {
        border-color: #94a3b8;
        background: #f8fafc;
    }

    @media (max-width: 768px) {
        .tickets-container {
            padding: 24px 18px 60px;
        }

        .page-header {
            flex-direction: column;
        }

        .tickets-table thead {
            display: none;
        }

        .tickets-table,
        .tickets-table tbody,
        .tickets-table tr,
        .tickets-table td {
            display: block;
            width: 100%;
        }

        .tickets-table tbody tr {
            margin-bottom: 16px;
            border-radius: 16px;
            box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
            padding: 16px;
        }

        .tickets-table tbody td {
            padding: 10px 0;
            position: relative;
            padding-left: 40%;
        }

        .tickets-table tbody td::before {
            content: attr(data-label);
            position: absolute;
            left: 0;
            width: 35%;
            font-size: 12px;
            font-weight: 600;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.06em;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="tickets-container mt-5">
    <div class="page-header">
        <div>
            <h2>Support Tickets</h2>
            <p>Create and manage your support tickets with our team.</p>
        </div>
        <button onclick="showCreateTicketModal()" class="action-button">
            <i class="fa-light fa-plus"></i>
            Create Ticket
        </button>
    </div>

    {% if tickets %}
    <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="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-secondary">
                <i class="fa-light fa-rotate"></i>
                <span>Refresh</span>
            </button>
        </div>
    </div>
    <div class="table-card">
        <div class="table-responsive">
            <table class="tickets-table" id="tickets-table">
                <thead>
                    <tr>
                        <th>Title</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-label="Title" data-title="{{ ticket[1] }}">
                            <strong>{{ ticket[1] }}</strong>
                        </td>
                        <td data-label="Priority" data-priority="{{ ticket[3] }}">
                            <span class="priority-badge priority-{{ ticket[3] }}">{{ ticket[3]|title }}</span>
                        </td>
                        <td data-label="Status" data-status="{{ ticket[4] }}">
                            <span class="status-badge status-{{ ticket[4]|replace('_', '-') }}">{{
                                ticket[4]|replace('_', ' ')|title }}</span>
                        </td>
                        <td data-label="Created" 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-label="Updated" data-updated-date="{{ ticket[6].isoformat() if ticket[6] else '' }}">{{
                            ticket[6].strftime('%Y-%m-%d %H:%M') if ticket[6] else '—' }}</td>
                        <td data-label="Action">
                            <a href="{{ url_for('company.view_support_ticket', ticket_id=ticket[0]) }}"
                                class="view-link" style="position: relative;">
                                View
                                {% if ticket[7] and ticket[7] > 0 %}
                                <span class="unread-badge">{{ ticket[7] if ticket[7] <= 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>
    {% else %}
    <div class="table-card">
        <div class="empty-state">
            <i class="fa-light fa-ticket"></i>
            <p>No support tickets yet. Create your first ticket to get started.</p>
        </div>
    </div>
    {% endif %}
</div>

<!-- Create Ticket Modal -->
<div id="createTicketModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Create Support Ticket</h3>
            <button onclick="hideCreateTicketModal()" class="close-modal">&times;</button>
        </div>
        <form id="createTicketForm">
            <div class="form-group">
                <label for="ticketTitle">Title *</label>
                <input type="text" id="ticketTitle" name="title" required placeholder="Enter ticket title">
            </div>
            <div class="form-group">
                <label for="ticketPriority">Priority *</label>
                <select id="ticketPriority" name="priority" required>
                    <option value="low">Low</option>
                    <option value="medium" selected>Medium</option>
                    <option value="high">High</option>
                    <option value="urgent">Urgent</option>
                </select>
            </div>
            <div class="form-group">
                <label for="ticketReason">Reason/Description *</label>
                <textarea id="ticketReason" name="reason" required
                    placeholder="Describe your issue or question..."></textarea>
            </div>
            <div class="form-actions">
                <button type="button" onclick="hideCreateTicketModal()" class="btn-secondary">Cancel</button>
                <button type="submit" class="action-button">Create Ticket</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    function showCreateTicketModal() {
        document.getElementById('createTicketModal').classList.add('active');
    }

    function hideCreateTicketModal() {
        document.getElementById('createTicketModal').classList.remove('active');
        document.getElementById('createTicketForm').reset();
    }

    document.getElementById('createTicketForm').addEventListener('submit', async function (e) {
        e.preventDefault();

        const formData = {
            title: document.getElementById('ticketTitle').value.trim(),
            priority: document.getElementById('ticketPriority').value,
            reason: document.getElementById('ticketReason').value.trim()
        };

        if (!formData.title || !formData.reason) {
            alert('Please fill in all required fields');
            return;
        }

        try {
            const response = await fetch('/company/support-tickets/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const data = await response.json();

            if (data.success) {
                window.location.href = `/company/support-tickets/${data.ticket_id}`;
            } else {
                alert(data.error || 'Failed to create ticket');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred while creating the ticket');
        }
    });

    // Close modal on outside click
    document.getElementById('createTicketModal').addEventListener('click', function (e) {
        if (e.target === this) {
            hideCreateTicketModal();
        }
    });

    // Filters and Pagination
    {% if tickets %}
    (function () {
        const tableBody = document.querySelector('#tickets-table tbody');
        const filterTitleInput = document.getElementById('filterTitle');
        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]?.getAttribute('data-title') || cells[0]?.textContent || '').trim().toLowerCase(),
                priority: (cells[1]?.getAttribute('data-priority') || '').toLowerCase(),
                status: (cells[2]?.getAttribute('data-status') || '').toLowerCase(),
                created: cells[3]?.getAttribute('data-created-date') || '',
                updated: cells[4]?.getAttribute('data-updated-date') || ''
            };
        });

        function getFilteredTickets() {
            const titleSearch = (filterTitleInput.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 (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, filterPrioritySelect, filterStatusSelect].forEach(input => {
            input.addEventListener('input', () => {
                currentPage = 1;
                renderTable();
            });
            input.addEventListener('change', () => {
                currentPage = 1;
                renderTable();
            });
        });

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

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