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

{% block extra_css %}
<style>
    body {
        background: #f5f7fb;
    }

    .groups-container {
        padding: 32px 24px 80px;
        max-width: 1200px;
        margin: 0 auto;
    }

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

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

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

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

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

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

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

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

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

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

    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 23%;
        width: 100%;
        height: 100%;
        background: none;
        overflow-y: hidden;
        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);
        border: 1px solid rgba(148, 163, 184, 0.12);
    }

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

    .contacts-list {
        max-height: 320px;
        overflow-y: auto;
        border: 1px solid #cbd5f5;
        border-radius: 12px;
        padding: 12px;
        margin-top: 12px;
        background: #f8fafc;
    }

    .contact-item {
        display: flex;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid rgba(148, 163, 184, 0.16);
        gap: 10px;
    }

    .contact-item:last-child {
        border-bottom: none;
    }

    .contact-item input[type="checkbox"] {
        width: 18px;
        height: 18px;
    }

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

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

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

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

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

    #groupDetails h4 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #0f172a;
        font-size: 1.5em;
        border-bottom: 1px solid #e2e8f0;
        padding-bottom: 5px;
    }

    #groupDetails p {
        margin-bottom: 15px;
        color: #475569;
        font-size: 0.95em;
    }

    #groupDetails h5 {
        margin-top: 20px;
        margin-bottom: 10px;
        color: #0f172a;
        font-size: 1.2em;
    }

    #groupDetails ul {
        list-style: disc;
        padding-left: 20px;
        margin-top: 0;
    }

    #groupDetails li {
        margin-bottom: 8px;
        color: #64748b;
        line-height: 1.5;
    }

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

        .header-actions {
            flex-direction: column;
            align-items: stretch;
        }

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

        .groups-table thead {
            display: none;
        }

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

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

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

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

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

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

{% block content %}
<div class="groups-container">
    <div class="header-actions">
        <div class="header-content" style="display: block;">
            <h2>Contact Groups</h2>
            <p>Organize your contacts into reusable cohorts for campaigns and calls.</p>
        </div>
        <div class="action-buttons">
            <button onclick="showAddGroupModal()" class="action-button primary">
                <i class="fa-light fa-plus"></i> Create Group
            </button>
        </div>
    </div>

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

    <div class="table-card">
        <div class="table-title-bar">
            <h3>Group Directory</h3>
        </div>
        <table class="groups-table">
            <thead>
                <tr>
                    <th>Group Name</th>
                    <th>Number of Contacts</th>
                    <th>Created Date</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="groupsList">
                <!-- Groups will be loaded here -->
            </tbody>
        </table>
    </div>

    <div id="groupsPagination"></div>

    <!-- Add Group Modal -->
    <div id="addGroupModal" class="modal">
        <div class="modal-content">
            <h3>Create Contact Group</h3>
            <form id="addGroupForm">
                <div class="form-group">
                    <label>Group Name</label>
                    <input type="text" id="groupName" required class="form-control">
                </div>
                <div class="form-group">
                    <label>Select Contacts</label>
                    <div class="contacts-list" id="contactsList">
                        <!-- Contacts will be loaded here -->
                    </div>
                </div>

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

    <!-- View Group Modal -->
    <div id="viewGroupModal" class="modal">
        <div class="modal-content">
            <h3>Group Details</h3>
            <div id="groupDetails">
                <!-- Group details will be loaded here -->
            </div>
            <div class="mt-3" style="text-align: end;">
                <button type="button" onclick="hideViewGroupModal()" class="action-button primary">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let groupsPerPage = 10;
    let currentGroupsPage = 1;
    let groupsData = [];
    let contactsData = [];

    async function loadGroups() {
        try {
            const response = await fetch('/company/contact-groups/list');
            const data = await response.json();
            if (data.success) {
                groupsData = data.groups;
                currentGroupsPage = 1;
                renderGroupsTable();
            }
        } catch (error) {
            console.error('Error loading groups:', error);
        }
    }

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

    function renderGroupsTable(filteredGroups = null) {
        const data = filteredGroups || groupsData;
        const start = (currentGroupsPage - 1) * groupsPerPage;
        const end = start + groupsPerPage;
        const pageGroups = data.slice(start, end);

        const groupsList = document.getElementById('groupsList');
        if (pageGroups.length === 0) {
            groupsList.innerHTML = `
                <tr>
                    <td colspan="4" class="text-center">No groups found</td>
                </tr>
            `;
        } else {
            groupsList.innerHTML = pageGroups.map(group => `
                <tr>
                    <td data-label="Group Name"><span class="group-name">${group.name}</span></td>
                    <td data-label="Number of Contacts">${group.contact_count}</td>
                    <td data-label="Created Date">${new Date(group.created_at).toLocaleDateString()}</td>
                    <td data-label="Actions">
                        <div class="actions-cell">
                            <button onclick="viewGroup('${group.id}')" class="action-button secondary">
                                <i class="fa-light fa-eye"></i>
                            </button>
                            <button onclick="deleteGroup('${group.id}')" class="action-button danger">
                                <i class="fa-light fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        renderGroupsPagination(data);
    }

    function renderContactsList() {
        const contactsList = document.getElementById('contactsList');
        contactsList.innerHTML = contactsData.map(contact => `
            <div class="contact-item">
                <input type="checkbox" id="contact_${contact[0]}" style="width:20px" value="${contact[0]}">
                <label for="contact_${contact[0]}">${contact[1]} (${contact[2]})</label>
            </div>
        `).join('');
    }

    function renderGroupsPagination(data = null) {
        const totalGroups = (data || groupsData).length;
        const totalPages = Math.ceil(totalGroups / groupsPerPage);
        let html = '';

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

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

    function changeGroupsPage(delta) {
        const totalPages = Math.ceil(groupsData.length / groupsPerPage);
        currentGroupsPage += delta;
        if (currentGroupsPage < 1) currentGroupsPage = 1;
        if (currentGroupsPage > totalPages) currentGroupsPage = totalPages;
        renderGroupsTable();
    }

    function showAddGroupModal() {
        document.getElementById('addGroupModal').style.display = 'block';
        loadContacts();
    }

    function hideAddGroupModal() {
        document.getElementById('addGroupModal').style.display = 'none';
        document.getElementById('addGroupForm').reset();
    }

    function showViewGroupModal() {
        document.getElementById('viewGroupModal').style.display = 'block';
    }

    function hideViewGroupModal() {
        document.getElementById('viewGroupModal').style.display = 'none';
    }

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

        const selectedContacts = Array.from(document.querySelectorAll('#contactsList input[type="checkbox"]:checked'))
            .map(checkbox => checkbox.value);

        if (selectedContacts.length === 0) {
            showNotification('Please select at least one contact', 'error');
            return;
        }

        const data = {
            name: document.getElementById('groupName').value,
            contact_ids: selectedContacts
        };

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

            const result = await response.json();
            if (result.success) {
                showNotification('Group created successfully!', 'success');
                hideAddGroupModal();
                loadGroups();
            } else {
                showNotification('Error: ' + result.error, 'error');
            }
        } catch (error) {
            showNotification('Error creating group: ' + error.message, 'error');
        }
    });

    async function viewGroup(groupId) {
        try {
            const response = await fetch(`/company/contact-groups/${groupId}`);
            const data = await response.json();
            if (data.success) {
                const group = data.group;
                document.getElementById('groupDetails').innerHTML = `
                    <h4>${group.name}</h4>
                    <p>Created: ${new Date(group.created_at).toLocaleDateString()}</p>
                    <h5>Contacts in this group:</h5>
                    <ul>
                        ${group.contacts.map(contact => `
                            <li>${contact.name} (${contact.phone_number})</li>
                        `).join('')}
                    </ul>
                `;
                showViewGroupModal();
            }
        } catch (error) {
            showNotification('Error loading group details: ' + error.message, 'error');
        }
    }

    async function deleteGroup(groupId) {
        if (!confirm('Are you sure you want to delete this group?')) {
            return;
        }

        try {
            const response = await fetch(`/company/contact-groups/${groupId}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            if (result.success) {
                showNotification('Group deleted successfully', 'success');
                loadGroups();
            } else {
                showNotification('Error: ' + result.error, 'error');
            }
        } catch (error) {
            showNotification('Error deleting group: ' + error.message, 'error');
        }
    }

    document.getElementById('searchGroups').addEventListener('input', (e) => {
        const searchTerm = e.target.value.toLowerCase();
        const filteredGroups = groupsData.filter(group =>
            group.name.toLowerCase().includes(searchTerm)
        );
        currentGroupsPage = 1;
        renderGroupsTable(filteredGroups);
        renderGroupsPagination(filteredGroups);
    });

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