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

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

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

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

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

    .action-buttons {
        display: flex;
        gap: 12px;
    }

    .action-button {
        padding: 12px 18px;
        border: none;
        border-radius: 12px;
        cursor: pointer;
        font-size: 15px;
        font-weight: 600;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 10px;
        text-decoration: none;
    }

    .action-button.primary {
        background: linear-gradient(135deg, #1d4ed8, #2563eb);
        color: #ffffff;
        box-shadow: 0 12px 24px rgba(37, 99, 235, 0.25);
    }

    .action-button.primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 16px 30px rgba(37, 99, 235, 0.3);
    }

    .action-button.secondary {
        background: #e2e8f0;
        color: #0f172a;
    }

    .action-button.secondary:hover {
        background: #cbd5f5;
    }

    .action-button.danger {
        background: rgba(248, 113, 113, 0.15);
        color: #b91c1c;
    }

    .action-button.danger:hover {
        background: rgba(248, 113, 113, 0.25);
    }

    .search-wrapper {
        margin-bottom: 20px;
    }

    .search-box {
        width: 100%;
        max-width: 360px;
        padding: 12px 16px;
        border: 1px solid #cbd5f5;
        border-radius: 12px;
        background: #f8fafc;
        color: #0f172a;
        font-size: 15px;
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .search-box:focus {
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
        outline: none;
        background: #fff;
    }

    .table-card {
        background: #ffffff;
        border-radius: 18px;
        box-shadow: 0 35px 65px rgba(15, 23, 42, 0.06);
        overflow: hidden;
        border: 1px solid rgba(148, 163, 184, 0.12);
    }

    .table-title-bar {
        padding: 18px 24px;
        border-bottom: 1px solid rgba(148, 163, 184, 0.18);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .table-title-bar h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #0f172a;
    }

    .contacts-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
    }

    .contacts-table thead th {
        background: #f8fafc;
        padding: 16px 20px;
        text-align: left;
        font-size: 13px;
        letter-spacing: 0.04em;
        text-transform: uppercase;
        color: #64748b;
        border-bottom: 1px solid rgba(148, 163, 184, 0.18);
    }

    .contacts-table tbody tr {
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .contacts-table tbody tr:hover {
        transform: translateY(-2px);
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
    }

    .contacts-table tbody tr + tr td {
        border-top: 1px solid rgba(148, 163, 184, 0.12);
    }

    .contacts-table tbody td {
        padding: 18px 20px;
        font-size: 15px;
        color: #1f2937;
        background: #ffffff;
    }

    .contact-name {
        font-weight: 600;
        color: #0f172a;
    }

    .contact-meta {
        font-size: 13px;
        color: #64748b;
        display: block;
        margin-top: 4px;
    }

    .contacts-table .actions-cell {
        display: flex;
        gap: 10px;
    }

    .contacts-table .actions-cell .action-button {
        padding: 10px 14px;
        border-radius: 10px;
        box-shadow: none;
    }

    .import-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(15, 23, 42, 0.35);
        z-index: 1050;
        overflow-y: auto;
    }

    .modal-content {
        background: white;
        width: 520px;
        margin: 80px auto;
        padding: 28px;
        border-radius: 18px;
        box-shadow: 0 35px 65px rgba(15, 23, 42, 0.25);
    }

    .modal-content h3 {
        margin-top: 0;
        color: #0f172a;
        font-weight: 700;
    }

    .sample-file {
        margin-top: 16px;
        padding: 16px;
        background: #f8fafc;
        border-radius: 12px;
        border: 1px dashed rgba(37, 99, 235, 0.35);
    }

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

    .modal-content .form-control {
        width: 100%;
        padding: 12px;
        border: 1px solid #cbd5f5;
        border-radius: 12px;
        background: #f8fafc;
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .modal-content .form-control:focus {
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
        outline: none;
        background: #fff;
    }

    #contactsPagination {
        margin-top: 24px;
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        align-items: center;
    }

    #contactsPagination button {
        background: #ffffff;
        color: #0f172a;
        border: 1px solid rgba(148, 163, 184, 0.28);
        border-radius: 10px;
        padding: 10px 18px;
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.2s ease;
    }

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

    #contactsPagination button[disabled] {
        background: #f1f5f9;
        color: #94a3b8;
        cursor: not-allowed;
        border-color: rgba(148, 163, 184, 0.2);
    }

    .pagination-info {
        color: #475569;
        font-weight: 600;
    }

    @media (max-width: 768px) {
        .header-actions {
            flex-direction: column;
            align-items: stretch;
        }

        .action-buttons {
            flex-wrap: wrap;
        }

        .contacts-table thead {
            display: none;
        }

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

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

        .contacts-table tbody td {
            padding: 14px 18px;
            position: relative;
        }

        .contacts-table tbody td::before {
            content: attr(data-label);
            display: block;
            margin-bottom: 6px;
            font-size: 12px;
            font-weight: 600;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.06em;
        }

        .contacts-table .actions-cell {
            justify-content: flex-start;
        }

        .search-box {
            max-width: 100%;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="contacts-container">
    <div class="header-actions">
        <div class="header-content" style="display: block;">
            <h2>Contacts</h2>
            <p>Manage, import, and organize the people in your campaigns.</p>
        </div>
        <div class="action-buttons">
            <button onclick="showImportModal()" class="action-button primary">
                <i class="fa-light fa-upload"></i> Import Contacts
            </button>
            <button onclick="showAddContactModal()" class="action-button primary">
                <i class="fa-light fa-plus"></i> Add Contact
            </button>
        </div>
    </div>

    <div class="search-wrapper">
        <input type="text" id="searchContacts" class="search-box" placeholder="Search contacts...">
    </div>

    <div class="table-card">
        <div class="table-title-bar">
            <h3>Contact Directory</h3>
        </div>
        <table class="contacts-table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Phone Number</th>
                    <th>Email</th>
                    <th>Created Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="contactsList">
                <!-- Contacts will be loaded here -->
            </tbody>
        </table>
    </div>

    <div id="contactsPagination"></div>

    <!-- Import Modal -->
    <div id="importModal" class="import-modal">
        <div class="modal-content">
            <h3>Import Contacts</h3>
            <form id="importForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select File</label>
                    <input type="file" id="contactFile" accept=".csv,.xlsx" class="form-control">
                    <small class="text-muted">Supported formats: CSV, Excel</small>
                </div>

                <div class="sample-file">
                    <p>Download sample file format:</p>
                    <a href="{{ url_for('static', filename='samples/contacts_template.csv') }}" style="margin-right: 10px;" download>
                        <i class="fa-light fa-download"></i> CSV Template
                    </a>
                    <a href="{{ url_for('static', filename='samples/contacts_template.xlsx') }}" download>
                        <i class="fa-light fa-download"></i> Excel Template
                    </a>
                </div>

                <div style="margin-top:10px">
                    <button type="button" onclick="importContacts()" class="action-button primary">
                        Import
                    </button>
                    <button type="button" onclick="hideImportModal()" class="action-button primary">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Contact Modal -->
    <div id="addContactModal" class="import-modal">
        <div class="modal-content">
            <h3>Add Contact</h3>
            <form id="addContactForm">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" id="contactName" required class="form-control">
                </div>
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="tel" id="contactPhone" required class="form-control" placeholder="+1234567890">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" id="contactEmail" class="form-control">
                </div>

                <div class="mt-3">
                    <button type="submit" class="action-button primary">Save</button>
                    <button type="button" onclick="hideAddContactModal()" class="action-button primary">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let contactsPerPage = 10;
    let currentContactsPage = 1;
    let contactsData = [];

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

    function renderContactsTable(filteredContacts = null) {
        const data = filteredContacts || contactsData;
        const start = (currentContactsPage - 1) * contactsPerPage;
        const end = start + contactsPerPage;
        const pageContacts = data.slice(start, end);

        const contactsList = document.getElementById('contactsList');
        if (pageContacts.length === 0) {
            contactsList.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center">No contacts found</td>
                </tr>
            `;
        } else {
            contactsList.innerHTML = pageContacts.map(contact => `
                <tr>
                    <td data-label="Name">
                        <span class="contact-name">${contact[1]}</span>
                    </td>
                    <td data-label="Phone Number">
                        ${contact[2]}
                    </td>
                    <td data-label="Email">
                        ${contact[3] || '-'}
                    </td>
                    <td data-label="Created Date">
                        ${new Date(contact[4]).toLocaleDateString()}
                    </td>
                    <td data-label="Actions">
                        <div class="actions-cell">
                            <button onclick="editContact('${contact[0]}')" class="action-button secondary">
                                <i class="fa-light fa-edit"></i>
                            </button>
                            <button onclick="deleteContact('${contact[0]}')" class="action-button danger">
                                <i class="fa-light fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        renderContactsPagination(data);
    }

    function renderContactsPagination(data = null) {
        const totalContacts = (data || contactsData).length;
        const totalPages = Math.ceil(totalContacts / contactsPerPage);
        let html = '';

        if (totalPages > 1) {
            html += `<button onclick="changeContactsPage(-1)" ${currentContactsPage === 1 ? 'disabled' : ''}>Previous</button>`;
            html += `<span class="pagination-info">Page ${currentContactsPage} of ${totalPages}</span>`;
            html += `<button onclick="changeContactsPage(1)" ${currentContactsPage === totalPages ? 'disabled' : ''}>Next</button>`;
        }

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

    function changeContactsPage(delta) {
        const totalPages = Math.ceil(contactsData.length / contactsPerPage);
        currentContactsPage += delta;
        if (currentContactsPage < 1) currentContactsPage = 1;
        if (currentContactsPage > totalPages) currentContactsPage = totalPages;
        renderContactsTable();
    }

    function showImportModal() {
        document.getElementById('importModal').style.display = 'block';
    }

    function hideImportModal() {
        document.getElementById('importModal').style.display = 'none';
    }

    function showAddContactModal() {
        document.getElementById('addContactModal').style.display = 'block';
    }

    function hideAddContactModal() {
        document.getElementById('addContactModal').style.display = 'none';
    }

    async function importContacts() {
        const fileInput = document.getElementById('contactFile');
        if (!fileInput.files[0]) {
            alert('Please select a file to import');
            return;
        }

        const formData = new FormData();
        formData.append('file', fileInput.files[0]);

        try {
            const response = await fetch('/company/contacts/import', {
                method: 'POST',
                body: formData
            });

            const result = await response.json();
            if (result.success) {
                alert('Contacts imported successfully!');
                hideImportModal();
                loadContacts();
            } else {
                alert('Error: ' + result.error);
            }
        } catch (error) {
            alert('Error importing contacts: ' + error.message);
        }
    }

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

        const data = {
            name: document.getElementById('contactName').value,
            phone_number: document.getElementById('contactPhone').value,
            email: document.getElementById('contactEmail').value
        };

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

            const result = await response.json();
            if (result.success) {
                showNotification('Contact added successfully!', 'success');

                hideAddContactModal();
                loadContacts();
                document.getElementById('addContactForm').reset();
            } else {
                showNotification('Error: ' + result.error, 'error');

            }
        } catch (error) {
            showNotification('Error adding contact: ' + error.message, 'error');
        }
    });

    document.getElementById('searchContacts').addEventListener('input', (e) => {
        const searchTerm = e.target.value.toLowerCase();
        const filteredContacts = contactsData.filter(contact =>
            contact[1].toLowerCase().includes(searchTerm) ||
            contact[2].includes(searchTerm) ||
            (contact[3] && contact[3].toLowerCase().includes(searchTerm))
        );
        currentContactsPage = 1;
        renderContactsTable(filteredContacts);
        // Also update pagination for filtered results
        renderContactsPagination(filteredContacts);
    });

    async function editContact(contactId) {
        try {
            const contact = contactsData.find(c => c[0] === contactId);
            if (!contact) {
                alert('Contact not found');
                return;
            }

            // Set form values
            document.getElementById('contactName').value = contact[1];
            document.getElementById('contactPhone').value = contact[2];
            document.getElementById('contactEmail').value = contact[3] || '';

            showAddContactModal();

            const form = document.getElementById('addContactForm');
            
            // Remove any existing submit event listeners
            const newForm = form.cloneNode(true);
            form.parentNode.replaceChild(newForm, form);

            // Add new submit handler for update
            newForm.addEventListener('submit', async function updateHandler(e) {
                e.preventDefault();

                const data = {
                    name: document.getElementById('contactName').value,
                    phone_number: document.getElementById('contactPhone').value,
                    email: document.getElementById('contactEmail').value
                };

                try {
                    const response = await fetch(`/company/contacts/${contactId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });

                    const result = await response.json();
                    if (result.success) {
                        showNotification('Contact updated successfully!', 'success');

                        hideAddContactModal();
                        loadContacts();
                        // Reset form
                        newForm.reset();
                    } else {
                        showNotification('Error: ' + result.error, 'error');

                    }
                } catch (error) {
                    showNotification('Error updating contact: ' + error.message, 'error');
                    
                    
                }
            });
        } catch (error) {
            console.error('Error in editContact:', error);
            // alert('Error preparing to edit contact');
        }
    }

    async function deleteContact(contactId) {
        if (!confirm('Are you sure you want to delete this contact?')) {
            return;
        }

        try {
            const response = await fetch(`/company/contacts/${contactId}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            if (result.success) {
                showNotification('Contact deleted successfully', 'success');

                loadContacts();
            } else {
                showNotification('Error: ' + result.error, 'error');
            }
        } catch (error) {
            console.error('Error in deleteContact:', error);
            // alert('Error deleting contact: ' + error.message);
        }
    }

    document.addEventListener('DOMContentLoaded', loadContacts);
</script>
{% endblock %}