import { DataService } from './api.js';

document.addEventListener('DOMContentLoaded', () => {
    // --- 1. SELEÇÃO DE ELEMENTOS ---
    const pendingListContainer = document.getElementById('pending-list');
    const historyListContainer = document.getElementById('history-list');
    const tabPendentes = document.getElementById('tab-pendentes');
    const tabHistorico = document.getElementById('tab-historico');
    const contentPendentes = document.getElementById('content-pendentes');
    const contentHistorico = document.getElementById('content-historico');
    const calculatorView = document.getElementById('calculator-view');
    const welcomeView = document.getElementById('welcome-view');
    const clientNameEl = document.getElementById('calc-client-name');
    const serviceDetailsEl = document.getElementById('calc-service-details');
    const calculatorEl = document.getElementById('charge-calculator');
    const totalServicoEl = document.getElementById('calc-total-servico');
    const totalMesEl = document.getElementById('calc-total-mes');
    const finalizeBtn = document.getElementById('btn-finalize');
    const printBtn = document.getElementById('btn-print-report');
    const fullMonthlyFeeInput = document.getElementById('calc-mensalidade-cheia');
    const finalMonthlyFeeInput = document.getElementById('calc-mensalidade-valor');
    const proportionalCheck = document.getElementById('calc-proporcional-check');
    const proportionalControls = document.getElementById('proportional-controls');
    const proportionalStartDateInput = document.getElementById('proportional-start-date');
    const proportionalEndDateInput = document.getElementById('proportional-end-date');
    const proportionalResultArea = document.getElementById('proportional-result-area');
    const proportionalDetailsEl = document.getElementById('proportional-details');
    const applyProportionalBtn = document.getElementById('btn-apply-proportional');

    // --- 2. VARIÁVEIS DE ESTADO ---
    let currentActivity = null;
    let pendingActivities = [];
    let proportionalValue = 0;

    // --- 3. FUNÇÕES PRINCIPAIS ---

    function renderProjection(futureInstallments, fullMonthlyFee) {
    // --- PARTE 1: Lógica para a projeção na tela (continua a mesma) ---
    const projectionContainer = document.getElementById('billing-projection');
    const projectionWrapper = document.getElementById('billing-projection-container');
    if (!projectionWrapper || !projectionContainer) return;

    const shouldShowProjection = futureInstallments.length > 0 && (futureInstallments.length > 1 || (futureInstallments.length > 0 && futureInstallments[0].total.toFixed(2) !== fullMonthlyFee.toFixed(2)));
    projectionWrapper.classList.toggle('hidden', !shouldShowProjection);

    let screenHtml = '<div class="space-y-1">';
    futureInstallments.forEach((fatura, index) => {
        if (fatura.total > 0.01) {
            screenHtml += `<details class="bg-slate-50 border rounded-md"><summary class="p-2 cursor-pointer font-semibold flex justify-between text-sm"><span>${index + 1}ª Parcela:</span><span class="font-bold text-slate-900">R$ ${fatura.total.toFixed(2).replace('.', ',')}</span></summary><div class="p-3 border-t bg-white text-xs"><ul class="list-disc list-inside space-y-1 text-slate-600">${fatura.breakdown.map(item => `<li>${item}</li>`).join('')}</ul></div></details>`;
        }
    });
    if (fullMonthlyFee > 0 && shouldShowProjection) {
        const nextInstallment = futureInstallments.length + 1;
        screenHtml += `<div class="text-center text-xs font-semibold text-indigo-700 bg-indigo-50 p-2 rounded-md mt-2"><p>${nextInstallment}ª Parcela em diante: R$ ${fullMonthlyFee.toFixed(2).replace('.', ',')} (Apenas Mensalidade)</p></div>`;
    }
    screenHtml += '</div>';
    projectionContainer.innerHTML = screenHtml;

    // --- PARTE 2: Lógica para preencher a FATURA DE IMPRESSÃO (com a nova seção) ---
    const printClientName = document.getElementById('print-client-name');
    const printBillingPeriod = document.getElementById('print-billing-period');
    const printProjection = document.getElementById('print-projection');
    // Adicionamos o seletor para a nova área de detalhes
    const printServiceDetails = document.getElementById('print-service-details');

    if (printClientName && printBillingPeriod && printProjection && printServiceDetails && currentActivity) {
        // Preenche o nome do cliente e o período
        printClientName.textContent = clientNameEl.textContent;
        const startDate = new Date(currentActivity.date);
        const endDate = new Date(startDate);
        endDate.setMonth(startDate.getMonth() + futureInstallments.length - 1);
        printBillingPeriod.textContent = `Período de Referência: ${startDate.toLocaleDateString('pt-BR')} a ${endDate.toLocaleDateString('pt-BR')}`;
        
        // --- NOVO TRECHO ADICIONADO ---
        // Preenche os detalhes do serviço (Motivo e Itens Relevantes)
        let serviceDetailsHtml = `<p><strong>Motivo do Serviço:</strong> ${currentActivity.reason}</p>`;
        if (currentActivity.details && currentActivity.details.length > 0) {
            serviceDetailsHtml += `<p style="margin-top: 0.5rem; font-weight: bold;">Itens Relevantes:</p>`;
            serviceDetailsHtml += `<ul style="list-style-position: inside; padding-left: 5px; margin:0;">`;
            currentActivity.details.forEach(detail => {
                serviceDetailsHtml += `<li>${detail}</li>`;
            });
            serviceDetailsHtml += '</ul>';
        }
        printServiceDetails.innerHTML = serviceDetailsHtml;
        // --- FIM DO NOVO TRECHO ---

        // Gera a projeção detalhada das parcelas (lógica de duas colunas)
        let printHtml = '<div style="display: flex; flex-direction: column; gap: 15px;">';
        for (let i = 0; i < futureInstallments.length; i += 2) {
            const fatura1 = futureInstallments[i];
            const fatura2 = futureInstallments[i + 1];

            printHtml += '<div style="display: flex; gap: 15px; width: 100%; page-break-inside: avoid;">';
            if (fatura1 && fatura1.total > 0.01) {
                printHtml += `<div style="flex: 1; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;"><div style="padding: 8px; background-color: #f8fafc; font-weight: bold; display: flex; justify-content: space-between; font-size: 14px;"><span>${i + 1}ª Parcela:</span><span>R$ ${fatura1.total.toFixed(2).replace('.', ',')}</span></div><div style="padding: 12px; font-size: 12px;"><ul style="list-style-position: inside; padding-left: 5px; margin:0;">${fatura1.breakdown.map(item => `<li>${item}</li>`).join('')}</ul></div></div>`;
            }
            if (fatura2 && fatura2.total > 0.01) {
                 printHtml += `<div style="flex: 1; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;"><div style="padding: 8px; background-color: #f8fafc; font-weight: bold; display: flex; justify-content: space-between; font-size: 14px;"><span>${i + 2}ª Parcela:</span><span>R$ ${fatura2.total.toFixed(2).replace('.', ',')}</span></div><div style="padding: 12px; font-size: 12px;"><ul style="list-style-position: inside; padding-left: 5px; margin:0;">${fatura2.breakdown.map(item => `<li>${item}</li>`).join('')}</ul></div></div>`;
            } else {
                printHtml += '<div style="flex: 1;"></div>';
            }
            printHtml += '</div>';
        }
        if (fullMonthlyFee > 0 && shouldShowProjection) {
            const nextInstallment = futureInstallments.length + 1;
            printHtml += `<div style="text-align: center; font-size: 12px; font-weight: bold; color: #4338ca; background-color: #eef2ff; padding: 8px; border-radius: 6px; margin-top: 15px;"><p>${nextInstallment}ª Parcela em diante: R$ ${fullMonthlyFee.toFixed(2).replace('.', ',')} (Apenas Mensalidade)</p></div>`;
        }
        printHtml += '</div>';
        printProjection.innerHTML = printHtml;
    }
}
    
    function calculateTotalAndProjection() {
        let totalServico = 0;
        const charges = [];
        const fullFee = parseFloat(fullMonthlyFeeInput.value) || 0;
        const monthlyFeeToBill = parseFloat(finalMonthlyFeeInput.value) || 0;
        
        totalServico += fullFee; 

        calculatorEl.querySelectorAll('input[type="number"][data-charge-item]').forEach(inputValor => {
            if (inputValor.id === 'calc-mensalidade-valor') return; 
            const valor = parseFloat(inputValor.value) || 0;
            if (valor > 0) {
                totalServico += valor;
                const chargeItemName = inputValor.dataset.chargeItem;
                const labelElement = inputValor.closest('.grid').querySelector('label');
                const label = labelElement ? labelElement.textContent : chargeItemName;
                const selectParcelas = document.getElementById(`calc-${chargeItemName}-parcelas`);
                const numParcelas = selectParcelas ? parseInt(selectParcelas.value) || 1 : 1;
                charges.push({ label, valor, parcelas: numParcelas });
            }
        });
        
        const maxInstallments = charges.length > 0 ? Math.max(0, ...charges.map(c => c.parcelas)) : 0;
        const futureInstallments = [];
        
        if (fullFee > 0 || charges.length > 0) {
            for (let i = 1; i <= Math.max(1, maxInstallments); i++) {
                let monthTotal = (i === 1) ? monthlyFeeToBill : fullFee;
                let breakdown = [];
                
                if (monthTotal > 0) {
                    breakdown.push(`Mensalidade: R$ ${monthTotal.toFixed(2).replace('.',',')}`);
                }

                charges.forEach(charge => {
                    if (i <= charge.parcelas) {
                        const installmentValue = charge.valor / charge.parcelas;
                        monthTotal += installmentValue;
                        breakdown.push(`${charge.label}: R$ ${installmentValue.toFixed(2).replace('.',',')}`);
                    }
                });

                if (monthTotal > 0.01 || i <= maxInstallments) {
                    futureInstallments.push({ total: monthTotal, breakdown });
                }
            }
        }
        
        totalServicoEl.textContent = `R$ ${totalServico.toFixed(2).replace('.', ',')}`;
        totalMesEl.textContent = `R$ ${(futureInstallments[0]?.total || 0).toFixed(2).replace('.', ',')}`;
        renderProjection(futureInstallments, fullFee);
    }
    
    function calculateProportionalFee() {
        const startDate = new Date(proportionalStartDateInput.value + 'T00:00:00');
        const endDate = new Date(proportionalEndDateInput.value + 'T00:00:00');
        const fullFee = parseFloat(fullMonthlyFeeInput.value) || 0;

        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime()) || endDate < startDate || fullFee <= 0) {
            proportionalResultArea.classList.add('hidden');
            return;
        }

        const timeDiff = endDate.getTime() - startDate.getTime();
        const dayDiff = Math.round(timeDiff / (1000 * 3600 * 24));
        const daysInServiceMonth = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0).getDate();
        
        proportionalValue = (fullFee / daysInServiceMonth) * dayDiff;
        proportionalDetailsEl.innerHTML = `Calculando ${dayDiff} dias.<br><b>Valor Proporcional: R$ ${proportionalValue.toFixed(2).replace('.',',')}</b>`;
        proportionalResultArea.classList.remove('hidden');
    }

    function displayActivityDetails(activityId) {
        currentActivity = pendingActivities.find(act => act.id == activityId);
        if (!currentActivity) return;
        
        document.querySelectorAll('.notification-item').forEach(item => item.classList.remove('active'));
        document.querySelector(`.notification-item[data-id="${activityId}"]`).classList.add('active');
        clientNameEl.textContent = currentActivity.clientName;
        const serviceDate = new Date(currentActivity.date);
        const serviceDateString = serviceDate.toISOString().split('T')[0];
        
        // Bloco Novo e Detalhado
        let detailsHtml = `<p><strong>Motivo:</strong> ${currentActivity.reason}</p>`;

        // Verifica se existe o array 'details' vindo do backend
        if (currentActivity.details && currentActivity.details.length > 0) {
        detailsHtml += `<p class="font-semibold mt-2">Itens Relevantes:</p>`;
        detailsHtml += '<ul class="list-disc list-inside pl-4">';
        // Cria um item de lista para cada detalhe
        currentActivity.details.forEach(detail => {
        detailsHtml += `<li>${detail}</li>`;
    });
    detailsHtml += '</ul>';
    }

serviceDetailsEl.innerHTML = detailsHtml;
        calculatorView.classList.remove('hidden');
        welcomeView.classList.add('hidden');
        
        calculatorEl.querySelectorAll('input[type="number"]').forEach(input => input.value = '');
        calculatorEl.querySelectorAll('select').forEach(select => select.value = '1');
        
        proportionalCheck.checked = false;
        proportionalControls.classList.add('hidden');
        proportionalResultArea.classList.add('hidden');
        proportionalStartDateInput.value = serviceDateString;
        proportionalEndDateInput.value = new Date(serviceDate.getFullYear(), serviceDate.getMonth() + 1, 0).toISOString().split('T')[0];
        
        finalMonthlyFeeInput.dispatchEvent(new Event('input', { bubbles: true }));
    }

    async function loadPendingActivities() {
    const pendingListContainer = document.getElementById('pending-list');
    pendingListContainer.innerHTML = '<p class="p-4 text-center text-slate-500">Carregando...</p>';
    try {
        const result = await DataService.getPendingFinancial(); 
        pendingActivities = result.data;
        if (pendingActivities.length === 0) {
            pendingListContainer.innerHTML = '<p class="p-4 text-center text-slate-500">Nenhuma ficha pendente.</p>';
            return;
        }
        
        // Esta parte do código lê o array 'details' que o PHP envia e o exibe
        pendingListContainer.innerHTML = pendingActivities.map(act => `
            <div class="notification-item p-4 border-b cursor-pointer hover:bg-slate-50" data-id="${act.id}">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="font-bold text-slate-800">${act.clientName}</p>
                        <p class="text-sm text-slate-600 font-medium">${act.reason}</p>
                    </div>
                    <p class="text-xs text-slate-400 text-right">${new Date(act.date).toLocaleDateString('pt-BR')}</p>
                </div>
                <div class="mt-2 pl-2 text-xs text-indigo-700 space-y-1">
                    ${(act.details || []).map(detail => `<div><i class="fas fa-arrow-right fa-xs mr-2"></i>${detail}</div>`).join('')}
                </div>
            </div>`).join('');

        document.querySelectorAll('.notification-item').forEach(item => {
            item.addEventListener('click', () => displayActivityDetails(item.dataset.id));
        });
    } catch (error) {
        pendingListContainer.innerHTML = `<p class="p-4 text-center text-red-500">${error.message}</p>`;
    }
}

    async function loadBillingHistory() {
    historyListContainer.innerHTML = '<p class="p-4 text-center text-slate-500">Carregando histórico...</p>';
    try {
        const result = await DataService.getBilledActivities();
        if(!result.data || result.data.length === 0) {
            historyListContainer.innerHTML = '<p class="p-4 text-center text-slate-500">Nenhuma fatura no histórico.</p>';
            return;
        }
        historyListContainer.innerHTML = result.data.map(item => {
            if(!item.detalhes_faturamento) return '';
            const details = JSON.parse(item.detalhes_faturamento);
            const itemsHtml = (details.itens || []).map(d => `<li>${d.descricao}: R$ ${parseFloat(d.valorTotal).toFixed(2)} (${d.parcelas})</li>`).join('');
            
            // Adicionamos o botão de impressão com os dados da fatura embutidos
            return `
                <div class="bg-slate-50 border rounded-md mb-2">
                    <div class="p-3 flex justify-between items-center">
                        <details class="flex-grow">
                            <summary class="cursor-pointer font-semibold flex justify-between">
                                <span>${item.clientName}</span>
                                <span class="text-sm text-slate-500">${new Date(details.dataFaturamento).toLocaleDateString('pt-BR')}</span>
                            </summary>
                            <div class="mt-4 pt-4 border-t bg-white text-sm space-y-2 p-3">
                                <p><strong>Total do Serviço:</strong> R$ ${parseFloat(details.totalServico).toFixed(2)}</p>
                                <p><strong>Primeira Fatura:</strong> R$ ${parseFloat(details.totalPrimeiraFatura).toFixed(2)}</p>
                                <p class="font-semibold mt-2">Itens Faturados:</p>
                                <ul class="list-disc list-inside pl-2">${itemsHtml}</ul>
                            </div>
                        </details>
                        <button class="reprint-invoice-btn text-slate-400 hover:text-indigo-600 ml-4 p-2" title="Reimprimir Fatura" 
                                data-invoice-details='${JSON.stringify(item)}'>
                            <i class="fas fa-print fa-lg"></i>
                        </button>
                    </div>
                </div>`;
        }).join('');
    } catch (error) {
        historyListContainer.innerHTML = `<p class="p-4 text-center text-red-500">${error.message}</p>`;
    }
}
    
    function switchFinancialTab(activeTabId) {
        const tabs = [tabPendentes, tabHistorico];
        tabs.forEach(tab => {
            const isTabActive = tab.id === `tab-${activeTabId}`;
            tab.className = `financial-tab whitespace-nowrap py-3 px-1 border-b-2 font-medium text-sm ${isTabActive ? 'text-indigo-600 border-indigo-500' : 'text-gray-500 border-transparent hover:text-gray-700'}`;
        });
        contentPendentes.classList.toggle('hidden', activeTabId !== 'pendentes');
        contentHistorico.classList.toggle('hidden', activeTabId !== 'historico');
        if (activeTabId === 'pendentes') {
            loadPendingActivities();
        } else if (activeTabId === 'historico') {
            loadBillingHistory();
        }
    }
    // --- 4. LISTENERS ---
    // Listener para os botões de REIMPRESSÃO no histórico
historyListContainer.addEventListener('click', (e) => {
    const reprintButton = e.target.closest('.reprint-invoice-btn');
    if (reprintButton) {
        const invoiceData = JSON.parse(reprintButton.dataset.invoiceDetails);
        const billingDetails = JSON.parse(invoiceData.detalhes_faturamento);

        // Preenche a fatura de impressão com os dados históricos
        document.getElementById('print-client-name').textContent = invoiceData.clientName;
        document.getElementById('print-billing-period').textContent = `Fatura gerada em: ${new Date(billingDetails.dataFaturamento).toLocaleString('pt-BR')}`;
        
        let printHtml = `
            <p><strong>Total do Serviço:</strong> R$ ${parseFloat(billingDetails.totalServico).toFixed(2)}</p>
            <p><strong>Valor da 1ª Fatura:</strong> R$ ${parseFloat(billingDetails.totalPrimeiraFatura).toFixed(2)}</p>
            <h3 style="font-weight: bold; margin-top: 1rem; border-top: 1px solid #ccc; padding-top: 1rem;">Itens Faturados:</h3>
            <ul style="list-style-position: inside; padding-left: 5px; margin:0;">
                ${(billingDetails.itens || []).map(d => `<li>${d.descricao}: R$ ${parseFloat(d.valorTotal).toFixed(2)} (${d.parcelas})</li>`).join('')}
            </ul>
        `;
        document.getElementById('print-projection').innerHTML = printHtml;
        
        // Abre a janela de impressão
        window.print();
    }
});
    document.getElementById('logout-button-financeiro')?.addEventListener('click', () => {
        sessionStorage.removeItem('currentUser');
        window.location.href = 'login.html';
    });
    
    tabPendentes.addEventListener('click', () => switchFinancialTab('pendentes'));
    tabHistorico.addEventListener('click', () => switchFinancialTab('historico'));
    
    printBtn.addEventListener('click', () => {
        window.print();
    });
    
    document.getElementById('calc-cabo-metros')?.addEventListener('input', e => {
        const metros = parseFloat(e.target.value) || 0;
        document.getElementById('calc-cabo-valor').value = (metros * 5).toFixed(2);
        document.getElementById('calc-cabo-valor').dispatchEvent(new Event('input', { bubbles: true }));
    });

    proportionalCheck.addEventListener('change', () => {
        proportionalControls.classList.toggle('hidden', !proportionalCheck.checked);
        finalMonthlyFeeInput.value = fullMonthlyFeeInput.value;
        if (!proportionalCheck.checked) {
            proportionalResultArea.classList.add('hidden');
        } else {
            calculateProportionalFee();
        }
        finalMonthlyFeeInput.dispatchEvent(new Event('input', { bubbles: true }));
    });
    
    [fullMonthlyFeeInput, proportionalStartDateInput, proportionalEndDateInput].forEach(el => el.addEventListener('input', () => { if(proportionalCheck.checked) calculateProportionalFee() }));
    
    applyProportionalBtn.addEventListener('click', () => {
        finalMonthlyFeeInput.value = proportionalValue.toFixed(2);
        finalMonthlyFeeInput.dispatchEvent(new Event('input', { bubbles: true }));
    });

    calculatorEl.addEventListener('input', e => { if (e.target.matches('input, select')) calculateTotalAndProjection(); });
    
    finalizeBtn.addEventListener('click', async () => {
        if (!currentActivity) { alert('Erro: Nenhuma ficha de cliente está selecionada.'); return; }
        const confirmation = confirm(`Você confirma o faturamento para o cliente ${clientNameEl.textContent}? Esta ação não pode ser desfeita.`);
        if (!confirmation) return;
        const charges = [];
        const fullFee = parseFloat(fullMonthlyFeeInput.value) || 0;
        const monthlyFeeToBill = parseFloat(finalMonthlyFeeInput.value) || 0;
        let totalServico = fullFee;
        calculatorEl.querySelectorAll('input[type="number"][data-charge-item]').forEach(inputValor => {
            if (inputValor.id === 'calc-mensalidade-valor') return; 
            const valor = parseFloat(inputValor.value) || 0;
            if (valor > 0) {
                const chargeItemName = inputValor.dataset.chargeItem;
                const label = inputValor.closest('.grid').querySelector('label').textContent;
                const selectParcelas = document.getElementById(`calc-${chargeItemName}-parcelas`);
                const numParcelas = selectParcelas ? parseInt(selectParcelas.value) : 1;
                charges.push({ descricao: label, valorTotal: valor, parcelas: `${numParcelas}x` });
                totalServico += valor;
            }
        });
        if (monthlyFeeToBill > 0) {
            charges.push({ descricao: 'Mensalidade', valorTotal: monthlyFeeToBill, parcelas: '1x' });
        }
        const billingDetails = {
            totalServico,
            totalPrimeiraFatura: parseFloat(totalMesEl.textContent.replace('R$', '').replace(',', '.')) || 0,
            dataFaturamento: new Date().toISOString(),
            itens: charges
        };
        const payload = {
            activityId: currentActivity.id,
            billingDetails: JSON.stringify(billingDetails)
        };
        alert('Processando faturamento...');
        try {
            const result = await DataService.finalizeBilling(payload);
            alert(result.message);
            switchFinancialTab('pendentes');
            calculatorView.classList.add('hidden');
            welcomeView.classList.remove('hidden');
        } catch (error) {
            alert(`Erro ao finalizar a fatura: ${error.message}`);
        }
    });
    
    // --- 5. CARGA INICIAL ---
    switchFinancialTab('pendentes');
});