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

{% block extra_css %}
<link href="{{ url_for('static', filename='css/campaign.css') }}" rel="stylesheet">
<style>
    .campaigns-container {
        padding: 20px;
    }

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

    /* Update modal styles to match contacts page */
    .import-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
        background: white;
        width: 600px;
        margin: 100px auto;
        padding: 20px;
        border-radius: 8px;
        position: absolute;
        top: -83px;
        left: 28%;
        height: 93vh;
        overflow-y: auto;
    }

    /* Rest of your existing styles */
    .campaign-status {
        padding: 5px 10px;
        border-radius: 4px;
        font-size: 0.9em;
    }

    .status-draft {
        background: #f0f0f0;
    }

    .status-queued {
        background: #fff3cd;
    }

    .status-sending {
        background: #cce5ff;
    }

    .status-completed {
        background: #d4edda;
    }

    .status-failed {
        background: #f8d7da;
    }

    .contact-selection {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #ddd;
        padding: 10px;
        margin: 10px 0;
        border-radius: 4px;
    }

    .contact-item {
        padding: 8px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
    }

    .contact-item:hover {
        background: #f8f9fa;
    }

    .contact-checkbox {
        margin-right: 10px;
    }

    .select-all-container {
        padding: 10px;
        background: #f8f9fa;
        border-bottom: 2px solid #ddd;
        margin-bottom: 10px;
    }

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

    .form-control {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .mt-3 {
        margin-top: 1rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="campaigns-container">
    <div class="header-actions">
        <h2>Email Campaigns</h2>
        <button onclick="showNewCampaignModal()" class="action-button primary">
            <i class="fa-light fa-plus"></i> NEW CAMPAIGN
        </button>
    </div>

    <!-- Campaigns List -->
    <table class="data-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Subject</th>
                <th>Status</th>
                <th>Recipients</th>
                <th>Scheduled</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody id="campaignsList">
            <!-- Campaigns will be loaded here -->
        </tbody>
    </table>

    <div id="campaignsPagination" style="margin-top: 10px; text-align: right;"></div>

    <!-- New Campaign Modal - Updated structure to match contacts page -->
    <div id="campaignModal" class="import-modal">
        <div class="modal-content">
            <h3>Create New Campaign</h3>
            <form id="campaignForm">
                <div class="form-group">
                    <label>Campaign Name</label>
                    <input type="text" id="campaignName" required class="form-control"
                        placeholder="Enter campaign name">
                </div>

                <div class="form-group">
                    <label>Email Subject</label>
                    <input type="text" id="emailSubject" required class="form-control"
                        placeholder="Enter email subject">
                </div>

                <div class="form-group">
                    <label>Schedule (Optional)</label>
                    <input type="datetime-local" id="scheduleTime" class="form-control"
                        min="{{ (now()|tojson)[1:20].replace('T', 'T') if now else '' }}">
                </div>


                <div class="form-group">
                    <label>Select Recipients</label>
                    <div class="contact-selection">
                        <div class="select-all-container">
                            <input style="width: 20px !important;" type="checkbox" id="selectAllContacts"
                                onchange="toggleAllContacts()">
                            <label for="selectAllContacts">Select All Contacts</label>
                        </div>
                        <div id="contactsList" class="contacts-list">
                            <!-- Contacts will be loaded here -->
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>Email Content</label>
                    <textarea id="emailContent" required></textarea>
                </div>

                <div class="mt-3">
                    <button type="submit" class="action-button primary">Create Campaign</button>
                    <button type="button" onclick="hideCampaignModal()" class="action-button primary">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Campaign Detail Modal -->
    <div id="campaignDetailModal" class="import-modal campaign-detail-modal">
        <div class="modal-content">
            <h3>Campaign Details</h3>
            <div id="campaignDetailContent"></div>
            <div id="recipientsPagination" style="margin-top: 10px; text-align: right;"></div>
            <div class="mt-3">
                <button type="button" onclick="hideCampaignDetailModal()" class="action-button primary">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // Set min attribute to current date/time if not using Jinja
    document.addEventListener('DOMContentLoaded', function () {
        var input = document.getElementById('scheduleTime');
        if (input) {
            const now = new Date();
            // Format as yyyy-MM-ddTHH:mm
            const pad = n => n < 10 ? '0' + n : n;
            const formatted = now.getFullYear() + '-' +
                pad(now.getMonth() + 1) + '-' +
                pad(now.getDate()) + 'T' +
                pad(now.getHours()) + ':' +
                pad(now.getMinutes());
            input.min = formatted;
        }
    });
</script>
<!-- Include TinyMCE -->
<script>
    let contacts = [];
    let campaigns = []
    let recipientsPerPage = 5;
    let currentRecipientsPage = 1;
    let recipientsData = [];
    let campaignsPerPage = 5;
    let currentCampaignsPage = 1;
    let campaignsData = [];

    function showNewCampaignModal() {
        document.getElementById('campaignModal').style.display = 'block';
        loadContacts();
    }

    function hideCampaignModal() {
        document.getElementById('campaignModal').style.display = 'none';
        document.getElementById('campaignForm').reset();
        document.getElementById('emailContent').value = '';
    }

    function toggleAllContacts() {
        const checked = document.getElementById('selectAllContacts').checked;
        document.querySelectorAll('.contact-checkbox').forEach(checkbox => {
            checkbox.checked = checked;
        });
    }

    async function loadContacts() {
        try {
            const response = await fetch('/company/contacts/list');
            const data = await response.json();
            if (data.success) {
                contacts = data.contacts;
                displayContactsForSelection(contacts);
            }
        } catch (error) {
            console.error('Error loading contacts:', error);
            showNotification('Error loading contacts', 'error');
        }
    }

    function displayContactsForSelection(contacts) {
        const contactsList = document.getElementById('contactsList');
        contactsList.innerHTML = contacts.map(contact => `
        <div class="contact-item">
            <input style="width: 20px !important;" type="checkbox" class="contact-checkbox" value="${contact[0]}" id="contact_${contact[0]}">
            <label for="contact_${contact[0]}">
                <strong>${contact[1]}</strong>
                <span class="text-muted">(${contact[3] || contact[2]})</span>
            </label>
        </div>
    `).join('');
    }

    function loadCampaigns() {
        fetch('/company/campaigns/list')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    campaignsData = data.campaigns;
                    currentCampaignsPage = 1;
                    renderCampaignsTable();
                }
            })
            .catch(error => {
                showNotification('Error loading campaigns', 'error');
            });
    }

    function renderCampaignsTable() {
        const start = (currentCampaignsPage - 1) * campaignsPerPage;
        const end = start + campaignsPerPage;
        const pageCampaigns = campaignsData.slice(start, end);

        const campaignsList = document.getElementById('campaignsList');
        if (pageCampaigns.length === 0) {
            campaignsList.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center">No campaigns found</td>
                </tr>
            `;
        } else {
            campaignsList.innerHTML = pageCampaigns.map(campaign => {
                const createdAt = campaign[10] ? new Date(campaign[10]).toLocaleString() : '-';
                const scheduledAt = campaign[12] ? new Date(campaign[12]).toLocaleString() : '-';

                return `
                    <tr>
                        <td>${campaign[3].length > 25 ? campaign[3].substring(0, 25) + '...' : campaign[3]}</td>
                        <td>${campaign[4].length > 30 ? campaign[4].substring(0, 30) + '...' : campaign[4]}</td>
                        <td>
                            <span class="campaign-status status-${campaign[6]}">${campaign[6]}</span>
                        </td>
                        <td>${campaign[7] || 0}/${campaign[8]}</td>
                        <td>${scheduledAt}</td>
                        <td>${createdAt}</td>
                        <td style="display: flex; gap: 5px;">
                            <button onclick="window.location.href='/company/campaigns/${campaign[0]}/show'" class="action-button button-icon secondary">
                                <i class="fa-light fa-eye"></i>
                            </button>
                            ${(campaign[6] === 'draft' || campaign[6] === 'scheduled') ? `
                                <button onclick="deleteCampaign('${campaign[0]}')" class="action-button button-icon secondary">
                                    <i class="fa-light fa-trash"></i>
                                </button>
                            ` : ''}
                        </td>
                    </tr>
                `;
            }).join('');
        }

        renderCampaignsPagination();
    }

    function renderCampaignsPagination() {
        const totalPages = Math.ceil(campaignsData.length / campaignsPerPage);
        let html = '';

        if (totalPages > 1) {
            html += `<button onclick="changeCampaignsPage(-1)" ${currentCampaignsPage === 1 ? 'disabled' : ''}>Prev</button>`;
            html += ` Page ${currentCampaignsPage} of ${totalPages} `;
            html += `<button onclick="changeCampaignsPage(1)" ${currentCampaignsPage === totalPages ? 'disabled' : ''}>Next</button>`;
        }

        document.getElementById('campaignsPagination').innerHTML = html;
    }

    function changeCampaignsPage(delta) {
        const totalPages = Math.ceil(campaignsData.length / campaignsPerPage);
        currentCampaignsPage += delta;
        if (currentCampaignsPage < 1) currentCampaignsPage = 1;
        if (currentCampaignsPage > totalPages) currentCampaignsPage = totalPages;
        renderCampaignsTable();
    }

    document.getElementById('campaignForm').addEventListener('submit', async (e) => {
        e.preventDefault();

        const selectedContacts = Array.from(document.querySelectorAll('.contact-checkbox:checked')).map(cb => cb.value);
        if (selectedContacts.length === 0) {
            showNotification('Please select at least one recipient', 'error');
            return;
        }

        const scheduleTime = document.getElementById('scheduleTime').value;

        const data = {
            name: document.getElementById('campaignName').value,
            subject: document.getElementById('emailSubject').value,
            content: document.getElementById('emailContent').value,
            scheduled_at: scheduleTime ? scheduleTime : null,  // Only send if actually set
            contact_ids: selectedContacts
        };

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

            const result = await response.json();
            if (result.success) {
                showNotification('Campaign created successfully!', 'success');
                hideCampaignModal();
                loadCampaigns();
            } else {
                showNotification('Error: ' + result.error, 'error');
            }
        } catch (error) {
            showNotification('Error creating campaign: ' + error.message, 'error');
        }
    });

    document.addEventListener('DOMContentLoaded', loadCampaigns);

    function viewCampaign(campaignId) {
        fetch(`/company/campaigns/${campaignId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showCampaignDetailModal(data.campaign, data.contacts);
                } else {
                    showNotification('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                showNotification('Error loading campaign details: ' + error, 'error');
            });
    }

    function showCampaignDetailModal(campaign, contacts) {
        recipientsData = contacts;
        currentRecipientsPage = 1;
        renderCampaignDetailModal(campaign);
        renderRecipientsTable();
        document.getElementById('campaignDetailModal').style.display = 'block';
    }

    function renderCampaignDetailModal(campaign) {
        let html = `
        <div class="campaign-info">
            <p><strong>Name:</strong> ${campaign.name}</p>
            <p><strong>Subject:</strong> ${campaign.subject}</p>
            <p><strong>Status:</strong> <span class="status-badge status-${campaign.status}">${campaign.status}</span></p>
            <p><strong>Scheduled At:</strong> ${campaign.scheduled_at || '-'}</p>
            <p><strong>Created At:</strong> ${campaign.created_at || '-'}</p>
            <p><strong>Content:</strong></p>
            <div class="campaign-content-box">${campaign.content}</div>
        </div>
        <h4>Recipients</h4>
        <table class="recipients-table" id="recipientsTable">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Status</th>
                    <th>Error</th>
                </tr>
            </thead>
            <tbody id="recipientsTableBody">
                <!-- Recipients will be rendered here -->
            </tbody>
        </table>
        <div id="recipientsPagination" style="margin-top: 10px; text-align: right;font-size: 12px;"></div>
        
        <h4>Replies</h4>
        <div id="repliesList" class="replies-list">
            <!-- Replies will be loaded here -->
        </div>
    `;
        document.getElementById('campaignDetailContent').innerHTML = html;

        // Load replies
        loadCampaignReplies(campaign.id);
    }

    function renderRecipientsTable() {
        const start = (currentRecipientsPage - 1) * recipientsPerPage;
        const end = start + recipientsPerPage;
        const pageRecipients = recipientsData.slice(start, end);

        document.getElementById('recipientsTableBody').innerHTML = pageRecipients.map(c => `
        <tr>
            <td>${c.name}</td>
            <td>${c.email}</td>
            <td>
                <span class="status-badge status-${c.status}">
                    ${c.status}
                </span>
            </td>
            <td>
                ${c.status === 'failed' && c.error_message ? `<span class="error-message">${c.error_message}</span>` : ''}
            </td>
        </tr>
    `).join('');

        renderRecipientsPagination();
    }

    function renderRecipientsPagination() {
        const totalPages = Math.ceil(recipientsData.length / recipientsPerPage);
        let html = '';

        if (totalPages > 1) {
            html += `<button onclick="changeRecipientsPage(-1)" ${currentRecipientsPage === 1 ? 'disabled' : ''} class="action-button-pg primary">Prev</button>`;
            html += ` Page ${currentRecipientsPage} of ${totalPages} `;
            html += `<button onclick="changeRecipientsPage(1)" ${currentRecipientsPage === totalPages ? 'disabled' : ''} class="action-button-pg primary">Next</button>`;
        }

        document.getElementById('recipientsPagination').innerHTML = html;
    }

    function changeRecipientsPage(delta) {
        const totalPages = Math.ceil(recipientsData.length / recipientsPerPage);
        currentRecipientsPage += delta;
        if (currentRecipientsPage < 1) currentRecipientsPage = 1;
        if (currentRecipientsPage > totalPages) currentRecipientsPage = totalPages;
        renderRecipientsTable();
    }

    function hideCampaignDetailModal() {
        document.getElementById('campaignDetailModal').style.display = 'none';
    }

    function loadCampaignReplies(campaignId) {
        fetch(`/company/campaigns/${campaignId}/replies`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const repliesList = document.getElementById('repliesList');
                    if (data.replies.length === 0) {
                        repliesList.innerHTML = '<p class="text-muted">No replies yet</p>';
                    } else {
                        repliesList.innerHTML = data.replies.map(reply => `
                            <div class="reply-item">
                                <div class="reply-header">
                                    <strong>${reply.contact_email}</strong>
                                    <span class="reply-date">${reply.reply_date}</span>
                                </div>
                                <div class="reply-content">${reply.content}</div>
                            </div>
                        `).join('');
                    }
                }
            })
            .catch(error => {
                console.error('Error loading replies:', error);
            });
    }
</script>
{% endblock %}