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

{% block title %}Bookings{% endblock %}

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

    .page-header {
        margin-bottom: 24px;
    }

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

    .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 {
        flex: 1;
        border: none;
        background: transparent;
        outline: none;
        font-size: 14px;
        color: #0f172a;
    }

    .filters-toolbar .input-wrapper input::placeholder {
        color: #94a3b8;
    }

    .filters-toolbar .date-range .date-range-inputs {
        display: flex;
        align-items: center;
        gap: 10px;
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        padding: 8px 12px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
    }

    .filters-toolbar .date-range {
        grid-column: span 2;
    }

    .filters-toolbar .date-range-inputs input[type="date"] {
        border: none;
        background: transparent;
        padding: 6px 8px;
        font-size: 14px;
        color: #0f172a;
        outline: none;
        flex: 1;
    }

    .filters-toolbar .date-range-inputs .separator {
        color: #94a3b8;
        font-size: 14px;
    }

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

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

    .filters-toolbar .btn {
        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;
        display: flex;
        align-items: center;
        gap: 8px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
    }

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

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

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

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

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

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

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

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

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

    .status-badge.booking {
        background: rgba(34, 197, 94, 0.16);
        color: #15803d;
    }

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

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

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

        .filters-toolbar {
            grid-template-columns: 1fr;
        }

        .filters-toolbar .date-range {
            grid-column: span 1;
        }

        .bookings-table thead {
            display: none;
        }

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

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

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

        .bookings-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="bookings-container mt-5">
    <div class="page-header">
        <h2>Bookings</h2>
        <p>View and manage all bookings from your call campaigns.</p>
    </div>

    {% if bookings %}
    <div class="filters-toolbar">
        <div class="filter-input">
            <label for="searchContact">Contact</label>
            <div class="input-wrapper">
                <i class="fa-light fa-magnifying-glass"></i>
                <input type="text" id="searchContact" placeholder="Search contact name">
            </div>
        </div>
        <div class="filter-input">
            <label for="searchEmail">Email</label>
            <div class="input-wrapper">
                <i class="fa-light fa-envelope"></i>
                <input type="text" id="searchEmail" placeholder="Search email">
            </div>
        </div>
        <div class="filter-input">
            <label for="searchCampaign">Campaign</label>
            <div class="input-wrapper">
                <i class="fa-light fa-bullhorn"></i>
                <input type="text" id="searchCampaign" placeholder="Search campaign">
            </div>
        </div>
        <div class="filter-input date-range">
            <label>Date range</label>
            <div class="date-range-inputs">
                <input type="date" id="dateFrom">
                <span class="separator">→</span>
                <input type="date" id="dateTo">
            </div>
        </div>
        <div class="filter-action">
            <button id="refreshBookings" class="btn 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="bookings-table" id="bookings-table">
                <thead>
                    <tr>
                        <th>Contact Name</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Campaign</th>
                        <th>Meeting Date</th>
                        <th>Meeting Time</th>
                        <th>Details</th>
                        <th>Created</th>
                    </tr>
                </thead>
                <tbody>
                    {% for booking in bookings %}
                    <tr>
                        <td data-label="Contact Name">{{ booking[7] or '—' }}</td>
                        <td data-label="Phone">{{ booking[8] or '—' }}</td>
                        <td data-label="Email">{{ booking[1] or booking[9] or '—' }}</td>
                        <td data-label="Campaign">{{ booking[10] or '—' }}</td>
                        <td data-label="Meeting Date">{{ booking[2] or '—' }}</td>
                        <td data-label="Meeting Time">{{ booking[3] or '—' }}</td>
                        <td data-label="Details" data-details="{{ booking[4] or '' }}">
                            {% if booking[4] %}
                            <span class="status-badge booking" style="cursor: pointer;" onclick="showDetailsModal('{{ booking[4]|replace("'", "\\'")|replace('"', '&quot;') }}')">View</span>
                            {% else %}
                            —
                            {% endif %}
                        </td>
                        <td data-label="Created" data-created-date="{{ booking[6].isoformat() if booking[6] else '' }}">
                            {{ booking[6].strftime('%Y-%m-%d %H:%M') if booking[6] else '—' }}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        <div class="table-footer">
            <div class="pagination-info" id="bookings-count"></div>
            <div class="pagination-controls">
                <button type="button" class="pagination-button" id="bookings-prev">Previous</button>
                <span class="pagination-info" id="bookings-page-label">Page 1</span>
                <button type="button" class="pagination-button" id="bookings-next">Next</button>
            </div>
        </div>
    </div>
    {% else %}
    <div class="table-card">
        <div class="empty-state">
            <i class="fa-light fa-calendar-xmark"></i>
            <p>No bookings found yet.</p>
        </div>
    </div>
    {% endif %}
</div>

<!-- Details Modal -->
<div id="detailsModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;">
    <div style="background: white; padding: 24px; border-radius: 16px; max-width: 500px; width: 90%; max-height: 80vh; overflow-y: auto;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <h3 style="margin: 0; font-size: 20px; font-weight: 700;">Booking Details</h3>
            <button onclick="closeDetailsModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; color: #64748b;">&times;</button>
        </div>
        <div id="detailsContent" style="color: #475569; line-height: 1.6;"></div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
{% if bookings %}
<script>
    (function() {
        const tableBody = document.querySelector('#bookings-table tbody');
        const searchContactInput = document.getElementById('searchContact');
        const searchEmailInput = document.getElementById('searchEmail');
        const searchCampaignInput = document.getElementById('searchCampaign');
        const dateFromInput = document.getElementById('dateFrom');
        const dateToInput = document.getElementById('dateTo');
        const refreshButton = document.getElementById('refreshBookings');
        const prevBtn = document.getElementById('bookings-prev');
        const nextBtn = document.getElementById('bookings-next');
        const pageLabel = document.getElementById('bookings-page-label');
        const countLabel = document.getElementById('bookings-count');

        const rowsPerPage = 10;
        let currentPage = 1;

        const bookingRows = Array.from(document.querySelectorAll('#bookings-table tbody tr')).map(row => {
            const cells = row.querySelectorAll('td');
            const createdDate = cells[7]?.getAttribute('data-created-date') || '';
            const detailsText = cells[6]?.getAttribute('data-details') || '';
            
            return {
                contactName: (cells[0]?.textContent || '').trim(),
                phone: (cells[1]?.textContent || '').trim(),
                email: (cells[2]?.textContent || '').trim(),
                campaign: (cells[3]?.textContent || '').trim(),
                meetingDate: (cells[4]?.textContent || '').trim(),
                meetingTime: (cells[5]?.textContent || '').trim(),
                details: (cells[6]?.textContent || '').trim(),
                created: createdDate,
                detailsText: detailsText
            };
        });

        function getFilteredBookings() {
            const contactSearch = (searchContactInput.value || '').toLowerCase().trim();
            const emailSearch = (searchEmailInput.value || '').toLowerCase().trim();
            const campaignSearch = (searchCampaignInput.value || '').toLowerCase().trim();
            const dateFrom = dateFromInput.value;
            const dateTo = dateToInput.value;

            return bookingRows.filter(booking => {
                if (contactSearch && !booking.contactName.toLowerCase().includes(contactSearch)) {
                    return false;
                }
                if (emailSearch && !booking.email.toLowerCase().includes(emailSearch)) {
                    return false;
                }
                if (campaignSearch && !booking.campaign.toLowerCase().includes(campaignSearch)) {
                    return false;
                }
                if (dateFrom || dateTo) {
                    if (!booking.created) return false;
                    const bookingDate = new Date(booking.created);
                    if (dateFrom) {
                        const fromDate = new Date(dateFrom);
                        fromDate.setHours(0, 0, 0, 0);
                        if (bookingDate < fromDate) return false;
                    }
                    if (dateTo) {
                        const toDate = new Date(dateTo);
                        toDate.setHours(23, 59, 59, 999);
                        if (bookingDate > toDate) return false;
                    }
                }
                return true;
            });
        }

        function formatDate(dateStr) {
            if (!dateStr) return '—';
            try {
                const date = new Date(dateStr);
                if (!isNaN(date.getTime())) {
                    return date.toLocaleString(undefined, { 
                        year: 'numeric', 
                        month: '2-digit', 
                        day: '2-digit', 
                        hour: '2-digit', 
                        minute: '2-digit' 
                    });
                }
            } catch (e) {}
            return dateStr;
        }

        function renderTable() {
            const filtered = getFilteredBookings();
            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);

            tableBody.innerHTML = pageItems.map(booking => {
                const escapedDetails = booking.detailsText 
                    ? booking.detailsText.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '&quot;').replace(/\n/g, '\\n')
                    : '';
                const detailsBadge = booking.detailsText 
                    ? `<span class="status-badge booking" onclick="showDetailsModal('${escapedDetails}')" style="cursor: pointer;">View</span>`
                    : '—';
                
                return `
                    <tr>
                        <td data-label="Contact Name">${booking.contactName || '—'}</td>
                        <td data-label="Phone">${booking.phone || '—'}</td>
                        <td data-label="Email">${booking.email || '—'}</td>
                        <td data-label="Campaign">${booking.campaign || '—'}</td>
                        <td data-label="Meeting Date">${booking.meetingDate || '—'}</td>
                        <td data-label="Meeting Time">${booking.meetingTime || '—'}</td>
                        <td data-label="Details" data-details="${escapedDetails}">${detailsBadge}</td>
                        <td data-label="Created" data-created-date="${booking.created}">${formatDate(booking.created)}</td>
                    </tr>
                `;
            }).join('');

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

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

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

        [searchContactInput, searchEmailInput, searchCampaignInput].forEach(input => {
            input.addEventListener('input', () => {
                currentPage = 1;
                renderTable();
            });
        });

        if (dateFromInput) {
            dateFromInput.addEventListener('change', () => {
                currentPage = 1;
                renderTable();
            });
        }

        if (dateToInput) {
            dateToInput.addEventListener('change', () => {
                currentPage = 1;
                renderTable();
            });
        }

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

        renderTable();
    })();

    function showDetailsModal(details) {
        const content = document.getElementById('detailsContent');
        if (details) {
            // Replace escaped newlines and decode HTML entities
            const decoded = details.replace(/\\n/g, '\n').replace(/&quot;/g, '"').replace(/\\'/g, "'").replace(/\\\\/g, '\\');
            content.textContent = decoded;
        } else {
            content.textContent = 'No additional details available.';
        }
        document.getElementById('detailsModal').style.display = 'flex';
    }

    function closeDetailsModal() {
        document.getElementById('detailsModal').style.display = 'none';
    }

    // Close modal on outside click
    document.getElementById('detailsModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeDetailsModal();
        }
    });
</script>
{% endif %}
{% endblock %}

