// Partners Page
let partnersPageData = [];

async function renderPartners() {
    const content = document.getElementById('main-content');
    
    try {
        partnersPageData = await apiRequest('partners.php');
        
        content.innerHTML = `
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Lista de Parceiros</h3>
                <button class="btn btn-primary" onclick="openPartnerModal()" data-testid="button-new-partner">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    Novo Parceiro
                </button>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                ${partnersPageData.length > 0 ? partnersPageData.map(p => `
                    <div class="card" data-testid="card-partner-${p.id}">
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex items-center gap-3">
                                <div class="w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900 flex items-center justify-center">
                                    <svg class="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                                </div>
                                <div>
                                    <h4 class="font-semibold text-gray-800 dark:text-white">${p.name}</h4>
                                    <span class="badge ${p.active ? 'badge-income' : 'badge-expense'}">${p.active ? 'Ativo' : 'Inativo'}</span>
                                </div>
                            </div>
                            <div class="flex gap-1">
                                <button class="btn btn-outline btn-sm" onclick="openPartnerModal('${p.id}')" data-testid="button-edit-partner-${p.id}">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="deletePartner('${p.id}')" data-testid="button-delete-partner-${p.id}">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                </button>
                            </div>
                        </div>
                        <div class="space-y-2 text-sm">
                            ${p.phone ? `<p class="text-gray-600 dark:text-gray-300"><strong>Telefone:</strong> ${p.phone}</p>` : ''}
                            ${p.email ? `<p class="text-gray-600 dark:text-gray-300"><strong>Email:</strong> ${p.email}</p>` : ''}
                        </div>
                    </div>
                `).join('') : '<div class="col-span-full empty-state"><p>Nenhum parceiro cadastrado</p></div>'}
            </div>
        `;
        
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar parceiros: ${error.message}</p></div>`;
    }
}

function openPartnerModal(id = null) {
    const partner = id ? partnersPageData.find(p => p.id === id) : null;
    
    openModal(`
        <div class="p-6">
            <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">
                ${partner ? 'Editar Parceiro' : 'Novo Parceiro'}
            </h3>
            <form id="partner-form" onsubmit="savePartner(event, ${id ? `'${id}'` : null})">
                <div class="form-group">
                    <label class="form-label">Nome</label>
                    <input type="text" id="partner-name" class="form-input" required value="${partner?.name || ''}" data-testid="input-name">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Telefone</label>
                    <input type="text" id="partner-phone" class="form-input" value="${partner?.phone || ''}" data-testid="input-phone">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Email</label>
                    <input type="email" id="partner-email" class="form-input" value="${partner?.email || ''}" data-testid="input-email">
                </div>
                
                <div class="form-group">
                    <label class="flex items-center gap-2">
                        <input type="checkbox" id="partner-active" ${partner?.active !== false ? 'checked' : ''}>
                        <span class="form-label mb-0">Ativo</span>
                    </label>
                </div>
                
                <div class="flex gap-2 justify-end mt-6">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary" data-testid="button-submit">Salvar</button>
                </div>
            </form>
        </div>
    `);
}

async function savePartner(event, id = null) {
    event.preventDefault();
    
    const data = {
        name: document.getElementById('partner-name').value,
        phone: document.getElementById('partner-phone').value || null,
        email: document.getElementById('partner-email').value || null,
        isActive: document.getElementById('partner-active').checked
    };
    
    try {
        if (id) {
            await apiRequest(`partners.php?id=${id}`, 'PUT', data);
            showToast('Parceiro atualizado com sucesso!');
        } else {
            await apiRequest('partners.php', 'POST', data);
            showToast('Parceiro criado com sucesso!');
        }
        closeModal();
        renderPartners();
    } catch (error) {
        showToast(error.message, 'error');
    }
}

async function deletePartner(id) {
    if (!confirm('Tem certeza que deseja excluir este parceiro?')) return;
    
    try {
        await apiRequest(`partners.php?id=${id}`, 'DELETE');
        showToast('Parceiro excluído com sucesso!');
        renderPartners();
    } catch (error) {
        showToast(error.message, 'error');
    }
}
