const paymentList = document.getElementById('payment-list');
const paymentForm = document.getElementById('payment-form');
const paymentFormElement = document.getElementById('payment-form-element')
const addPaymentBtn = document.getElementById('add-payment-btn');
const cancelBtn = document.getElementById('cancel-btn');
const formError = document.getElementById('form-error')
const listError = document.getElementById('list-error')
const paymentIdInput = document.getElementById('payment-id');
const customerDropdown = document.getElementById('customer-dropdown');
const customerList = document.getElementById('customer-list');
const paidInput = document.getElementById('paid');
const creditInput = document.getElementById('credit');
const descriptionInput = document.getElementById('description');
const paymentFormDiv=document.getElementById('paymentFormDiv');
const historyTableDiv=document.getElementById('historyTableDiv');


const companyId=sessionStorage.getItem('companyId');

let payments = [];
let customers = [];
let selectedCustomerId;
let currentCustomerId;

async function getCustomers() {
    try {
        const response = await fetch(`/api/customers?companyId=${companyId}`); // Your customer API endpoint
        if(!response.ok){
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        customers = await response.json();

        console.log("customers are",customers);




     renderCustomerToTable( customers);

// additionally here there shall be list of customers and here shall add "vewi history" button with customerId and will callgetPaymentHistory(customerId) function

    } catch (error) {
        console.error('Error fetching customers:', error);
    }
}













function renderCustomerToTable(customersToShow) {
    const customerTable = document.getElementById('customerTable');
    customerTable.innerHTML = ''; // Clear existing table content
  
    // Create table header (optional but recommended)
    const headerRow = customerTable.insertRow();
    const headers = ["Name", "Phone No", "Balance", "Actions"]; // Add more headers as needed
    headers.forEach(headerText => {
      const headerCell = document.createElement('th');
      headerCell.textContent = headerText;
      headerRow.appendChild(headerCell);
    });
  
    customersToShow.forEach(customer => {
      const row = customerTable.insertRow();
  
      row.innerHTML = `
        <td>${customer.name}</td>
        <td>${customer.phone}</td>
        <td>
  <span style="color: ${customer.balance < 0 ? 'red' : 'green'};">
    ${customer.balance.toFixed(0)}
  </span>
</td>
        <td>

<div class="dropdown">
          <button class="dropdown-button">…</button>
          <div class="dropdown-content">
         <div> <button class="add-payment-btn">Add Payment</button></div>
        <div>  <button class="view-history-btn"> View History</button></div>
</div></div>
        </td>
      `;
  
      // Access buttons using querySelector or similar methods for event listeners
      const addPaymentBtn = row.querySelector('.add-payment-btn');
      addPaymentBtn.addEventListener('click', () => {
        showForm(null, customer.customerId); // Pass customerId to showForm
      });
  
      const viewHistoryBtn = row.querySelector('.view-history-btn');
      viewHistoryBtn.addEventListener('click', () => {
        currentCustomerId=customer.customerId;
        getPaymentHistory(customer.balance); // Fetch payment history for this customer
       
    
    });
    });

    actionMenu();// add event listner
  }



//Modify showForm function to accept customerId as an argument
function showForm(payment = null, customerId=null) {

    paymentFormDiv.style.display='block';
    paymentForm.style.display = 'block';
    formError.textContent = '';
    paymentFormElement.reset();
    customerDropdown.value = '';
  
  
    selectedCustomerId = customerId; // Use passed customerId or null
    customerList.style.display = 'none';
    customerDropdown.disabled = true;

    if (payment) {
        paymentIdInput.value = payment._id;
        customerDropdown.value = payment.customerId.name || payment.customerId;
        selectedCustomerId = payment.customerId._id || payment.customerId;
        paidInput.value = payment.paid;
        creditInput.value = payment.credit;
        descriptionInput.value = payment.description;
        customerDropdown.disabled = true;
    } else {
        customerDropdown.value = customers.find(c=>c.customerId === customerId)?.name||'';
     
    }
}

async function getPaymentHistory(balance) {

    
    try {
        const response = await fetch(`/api/payment-history/${currentCustomerId}`);
        if(!response.ok){
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        payments = await response.json();
        renderPaymentList(balance);
        historyTableDiv.style.display='block';
    } catch (error) {
        listError.textContent = 'Error fetching payment history: '+error.message;
        console.error('Error fetching payment history:', error);
    }
}

function renderPaymentList(balance) {

    if(payments.length<=0){

        alert("No history Found");
        return;
    }
    const historyTableBody = document.getElementById('historyTableBody');
    historyTableBody.innerHTML = '';

    const customerName = document.getElementById('customerName');
    const customerBalance = document.getElementById('customerBalance');
    
    customerName.innerHTML = `${payments[0].customerId.name}`;
    customerBalance.innerHTML = `${balance}`;
    
    // Change text color based on balance value
    customerBalance.style.color = balance > 0 ? '#28a745' : '#dc3545'; // Green if >0, Red if ≤0
    

    payments.forEach(payment => {
        const row = document.createElement('tr');


        const createdAtDate = new Date(payment.createdAt);


        row.innerHTML = `
         <td>${createdAtDate.toLocaleDateString()}</td>
          <td>${payment.credit}</td>
            <td>${payment.paid}</td>
           
            <td>${payment.description||''}</td>
            <td>


<div class="dropdown">
          <button class="dropdown-button2">…</button>
          <div class="dropdown-content">
         <div>   <button id="edit-btn" data-id="${payment._id}">Edit</button></div>
        <div>  <button id="delete-btn" data-id="${payment._id}">Delete</button></div>
</div></div>


              
               
            </td>
        `;

        historyTableBody.appendChild(row);
    });
    actionMenu2();// add event listner
    addEventListeners();
}

function addEventListeners() {
    document.querySelectorAll('#edit-btn').forEach(button => {
        button.addEventListener('click', () => {
            const paymentId = button.dataset.id;
            const payment = payments.find(p => p._id === paymentId);
            if (payment) {
                // Function to show edit form populated with payment details
              
              
                showForm(payment);
            }
        });
    });

    document.querySelectorAll('#delete-btn').forEach(button => {
        button.addEventListener('click', async () => {
            const paymentId = button.dataset.id;
            await deletePayment(paymentId);
        });
    });
}


async function savePayment(paymentData) {
    try {
       
        const method = paymentData._id ? 'PUT' : 'POST';
        const url = paymentData._id ? `/api/payment-history/${paymentData._id}` : `/api/payment-history/`;
        const response = await fetch(url, {
            method: method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(paymentData),
        });
        if(!response.ok){
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        alert("successfully updated")
      
      //  await getPaymentHistory();
        hideForm();
        getCustomers();

    } catch (error) {
        formError.textContent = 'Error saving payment: '+error.message;
        console.error('Error saving payment:', error);
    }
}

async function deletePayment(id) {
    try {
        const response = await fetch(`/api/payment-history/${id}`, { method: 'DELETE' });
        if(!response.ok){
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        alert("successfully Deleted")
        await getPaymentHistory();
    } catch (error) {
        listError.textContent = 'Error deleting payment: '+error.message;
        console.error('Error deleting payment:', error);
    }
}

function showForm2(payment = null) {
    paymentForm.style.display = 'block';
    formError.textContent = '';
    paymentFormElement.reset();
    customerDropdown.value = '';
    selectedCustomerId = null;
    customerList.style.display = 'none';

    if (payment) {
        paymentIdInput.value = payment._id;
        customerDropdown.value = payment.customerId.name || payment.customerId;
        selectedCustomerId = payment.customerId._id || payment.customerId;
        paidInput.value = payment.paid;
        creditInput.value = payment.credit;
        descriptionInput.value = payment.description||'';
    }
}

function hideForm() {
    const modal = document.getElementById("paymentFormDiv");
    modal.style.display = "none";
}

function addEventListeners3() {
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', () => {
           
            const id = btn.dataset.id;
            const payment = payments.find(p => p._id === id);
            if (payment) showForm(payment);
        });
    });

    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', async () => {
           
            const id = btn.dataset.id;
            await deletePayment(id);
        });
    });
}

customerDropdown.addEventListener('input', () => {
    const searchTerm = customerDropdown.value.toLowerCase();
    const filteredCustomers = customers.filter(customer =>
        customer.name.toLowerCase().includes(searchTerm)
    );
    renderCustomerList(filteredCustomers);
});

customerDropdown.addEventListener('blur', () => {
    setTimeout(() => {
        customerList.style.display = 'none';
    }, 200); // Small delay to allow click event to register
});

function renderCustomerList(customersToShow) {
    customerList.innerHTML = '';
    customerList.style.display = customersToShow.length ? 'block' : 'none';
    customersToShow.forEach(customer => {
        const li = document.createElement('li');
        li.textContent = customer.name;
        li.addEventListener('click', () => {
            customerDropdown.value = customer.name;
            selectedCustomerId = customer._id;
            customerList.style.display = 'none';
        });
        customerList.appendChild(li);
    });
}



cancelBtn.addEventListener('click', hideForm);

paymentFormElement.addEventListener('submit', async (e) => {
    e.preventDefault();
    if (!selectedCustomerId) {
        formError.textContent = 'Please select a customer.';
        return;
    }
    const paymentData = {
        _id: paymentIdInput.value || undefined,
        customerId: selectedCustomerId,
        paid: parseFloat(paidInput.value),
        credit: parseFloat(creditInput.value),
        description: descriptionInput.value,
    };
    await savePayment(paymentData);
    getCustomers();
});

//getCustomers().then(() => getPaymentHistory());
getCustomers();


// Get the close button element
const closeEditModal = document.getElementById("closeEditModal");
closeEditModal.addEventListener("click", closeEditPaymentModal);
// Function to close the modal
function closeEditPaymentModal() {
  const modal = document.getElementById("paymentFormDiv");
  modal.style.display = "none";
}

const closeHistoryModal = document.getElementById("closeHistoryModal");
closeHistoryModal.addEventListener("click", closeHistoryPaymentModal);
// Function to close the modal
function closeHistoryPaymentModal() {
  const modal = document.getElementById("historyTableDiv");
  modal.style.display = "none";
}


function actionMenu(){
    const dropdownButtons = document.querySelectorAll('.dropdown-button');

    dropdownButtons.forEach(button => {
      button.addEventListener('click', (event) => {
        const dropdownContent = event.target.nextElementSibling;
        dropdownContent.classList.toggle('show');
      });
    });


}

function actionMenu2(){
    const dropdownButtons = document.querySelectorAll('.dropdown-button2');

    dropdownButtons.forEach(button => {
      button.addEventListener('click', (event) => {
       
        const dropdownContent = event.target.nextElementSibling;
        dropdownContent.classList.toggle('show');
      });
    });


}

// Listen for clicks anywhere in the document
document.addEventListener('click', (event) => {
    const clickedElement = event.target; // Get the clicked element
  
    // Check if the click is outside the dropdown button and content
    if (!clickedElement.classList.contains('dropdown-button')&&!clickedElement.classList.contains('dropdown-button2') && !clickedElement.classList.contains('dropdown-content')) {
      // Hide all open dropdowns
      const openDropdowns = document.querySelectorAll('.dropdown-content.show');
     openDropdowns.forEach(dropdown => dropdown.classList.remove('show'));
    }
  });