$(document).ready(function() {
    const AJAX_URL = '/quanlybanhang/ajax/messaging_ajax.php';

    function initializeSelect2() {
        $('#template-search').select2({
            theme: 'bootstrap-5',
            allowClear: true,
            dropdownParent: $('#composer-pane'),
            ajax: {
                url: AJAX_URL,
                dataType: 'json',
                delay: 250,
                data: params => ({ action: 'search_templates', term: params.term }),
                processResults: data => ({ results: data.data || [] })
            }
        });

        $('#customer-group-select').select2({
            theme: 'bootstrap-5',
            dropdownParent: $('#composer-pane'),
            ajax: {
                url: AJAX_URL,
                dataType: 'json',
                data: () => ({ action: 'get_customer_groups' }),
                processResults: data => ({ results: data.data || [] })
            }
        });

        $('#customer-search').select2({
            theme: 'bootstrap-5',
            multiple: true,
            dropdownParent: $('#composer-pane'),
            ajax: {
                url: AJAX_URL,
                dataType: 'json',
                delay: 250,
                data: params => ({ action: 'search_customers', term: params.term }),
                processResults: data => ({ results: data.data || [] })
            }
        });
    }

    function loadHistory() {
        const tbody = $('#history-table tbody');
        tbody.html('<tr><td colspan="5" class="text-center p-5"><span class="spinner-border spinner-border-sm"></span> Đang tải lịch sử...</td></tr>');
        
        $.getJSON(AJAX_URL, { action: 'get_campaign_history' }, function(response) {
            tbody.empty();
            if (response.status === 'success' && response.data.length > 0) {
                response.data.forEach(campaign => {
                    const shortMessage = campaign.message_content.length > 50 ? campaign.message_content.substring(0, 50) + '...' : campaign.message_content;
                    tbody.append(`
                        <tr>
                            <td>${campaign.campaign_name}</td>
                            <td title="${campaign.message_content}">${shortMessage}</td>
                            <td>${campaign.recipient_details}</td>
                            <td class="text-center">${campaign.recipient_count}</td>
                            <td>${new Date(campaign.created_at).toLocaleString('vi-VN')}</td>
                        </tr>
                    `);
                });
            } else {
                tbody.append('<tr><td colspan="5" class="text-center p-5 text-muted">Chưa có lịch sử gửi tin.</td></tr>');
            }
        });
    }
    
    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        if (e.target.id === 'history-tab') {
            loadHistory();
        }
    });

    $('#template-search').on('select2:select', function(e) {
        const data = e.params.data;
        $('#message_content').val(data.content).trigger('input');
    });

    $('#message_content').on('input', function() {
        const length = $(this).val().length;
        const messages = Math.ceil(length / 160) || 1;
        $('#char-counter').text(`${length}/${messages * 160} ký tự (${messages} tin)`);
    });

    $('input[name="recipient_type"]').on('change', function() {
        if (this.value === 'group') {
            $('#recipient-group-container').show();
            $('#recipient-individual-container').hide();
        } else {
            $('#recipient-group-container').hide();
            $('#recipient-individual-container').show();
        }
    });

    $('#customer-group-select').on('change', function() {
        const groupId = $(this).val();
        if (!groupId) {
            $('#group-recipient-count').text('0');
            return;
        }
        $.getJSON(AJAX_URL, { action: 'get_group_count', group_id: groupId }, function(response) {
            $('#group-recipient-count').text(response.count || '0');
        });
    });

    $('#send-message-form').on('submit', function(e) {
        e.preventDefault();
        const button = $('#btn-send');
        const campaignData = {
            action: 'create_campaign',
            campaign_name: $('#campaign_name').val(),
            message_content: $('#message_content').val(),
            recipient_type: $('input[name="recipient_type"]:checked').val(),
            recipient_group: $('#customer-group-select').val(),
            recipient_individuals: $('#customer-search').val()
        };

        if ((campaignData.recipient_type === 'group' && !campaignData.recipient_group) || (campaignData.recipient_type === 'individual' && (!campaignData.recipient_individuals || campaignData.recipient_individuals.length === 0))) {
            alert('Vui lòng chọn ít nhất một người nhận.');
            return;
        }

        if (confirm('Bạn có chắc chắn muốn bắt đầu chiến dịch gửi tin này?')) {
            button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang xử lý...');
            $.ajax({
                url: AJAX_URL,
                type: 'POST',
                data: campaignData,
                dataType: 'json',
                success: function(response) {
                    alert(response.message);
                    if (response.status === 'success') {
                        $('#send-message-form')[0].reset();
                        $('#template-search, #customer-group-select, #customer-search').val(null).trigger('change');
                        $('#message_content').trigger('input');
                        $('#group-recipient-count').text('0');
                    }
                },
                error: () => alert('Đã có lỗi xảy ra, vui lòng thử lại.'),
                complete: () => button.prop('disabled', false).html('<i class="fas fa-rocket me-2"></i>Bắt đầu gửi chiến dịch')
            });
        }
    });
    
    initializeSelect2();
});