// SELECTORS 
const tableBody=document.querySelector("#table-body");

const addDonorBtn=document.querySelector("#add-donor-btn");
const donorForm=document.querySelector("#donor-form");

const donorModal=document.querySelector("#donor-modal")
const modalTitle=document.querySelector(".modal-title");

const bloodTypeSelect=document.querySelector("#blood-type");
const donorNameInput=document.querySelector("#donor-name");
const contactNumberInput=document.querySelector("#contact-number");
const ageInput=document.querySelector("#age");
const lastDonationDateInput=document.querySelector("#last-donation-date");

const searchForm=document.querySelector("#search-form");


// FUNCTIONS
const fetchDonorData=async()=>{
  const response= await fetch('../mocks/donorData.json')
  const donorData=await response.json()
  return donorData
}

function formatDateToYYYYMMDD(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

const renderTableRows=async (donorArray)=>{
let donorList;
if(!donorArray)
  donorList=await fetchDonorData()
else {
  donorList=[...donorArray]
}

  if(donorList){
  let tableRows='';
  donorList?.forEach(donor=>{
    tableRows+=
    `<tr id="row" data-row-number="${donor.id}">
        <th scope="row">${donor.id}</th>
        <td>${donor.donorName}</td>
        <td>${donor.age}</td>
        <td>${donor.bloodType}</td>
        <td>${donor.contactNumber}</td>
        <td>${new Date(donor.lastDonationDate).toLocaleDateString("en-US")}</td>
        <td>
        <div class="d-flex gap-1">
          <button id="edit-donor-btn" data-donor-id=${donor.id} type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#donor-modal"><img id="edit-donor-icon" data-donor-id=${donor.id} src="./assets/icons/pencil-square.svg" alt=""></button> 
          <button id="delete-donor-btn" data-donor-id=${donor.id} type="button" class="btn btn-danger btn-sm"><img id="delete-donor-icon" data-donor-id=${donor.id} src="./assets/icons/trash-can.svg" alt="delete icon"></button>
        </td>
        </div>
      </tr>
    `
  })

  tableBody.innerHTML=tableRows
}
}

const submitDonor=(e)=>{
e.preventDefault();

 const formData = new FormData(e.target);
 const bloodType = formData.get("blood-type");
 const donorName= formData.get("donor-name");
 const contactNumber = formData.get("contact-number");
 const age = formData.get("age");
 const lastDonationDate = new Date(formData.get("last-donation-date"));

 if(bloodType!=="" && donorName!=="" && contactNumber!=="" && age!=="" && lastDonationDate!==""){
  // EDIT Donor IF ID EXISTS ON FORM
  if(e.target.dataset.donorId) {
    const selectedRow=document.querySelector(`[data-row-number="${e.target.dataset.donorId}"]`)
 
    selectedRow.innerHTML=`<th scope="row">${e.target.dataset.donorId}</th>
    <td>${donorName}</td>
    <td>${age}</td>
    <td>${bloodType}</td>
    <td>${contactNumber}</td>
    <td>${lastDonationDate.toLocaleDateString('en-US')}</td>
    <td>
    <div class="d-flex gap-1">
      <button id="edit-donor-btn" data-donor-id=${e.target.dataset.donorId} type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#donor-modal"><img id="edit-donor-icon" data-donor-id=${e.target.dataset.donorId} src="./assets/icons/pencil-square.svg" alt=""></button> 
      <button id="delete-donor-btn" data-donor-id=${e.target.dataset.donorId} type="button" class="btn btn-danger btn-sm"><img id="delete-donor-icon" data-donor-id=${e.target.dataset.donorId} src="./assets/icons/trash-can.svg" alt="delete icon"></button>
      </div>
    </td>`

  }
  // ADD BLOOD IF THERE'S NO ID LINKED TO THE FORM
  else {
  const allRows=document.querySelectorAll("#row")
  const lastDonorId=Number(allRows[allRows.length-1].getAttribute("data-row-number"))
  const tableRow=
  `<tr id="row" data-row-number=${lastDonorId+1}>
      <th scope="row">${lastDonorId+1}</th>
      <td>${donorName}</td>
      <td>${age}</td>
      <td>${bloodType}</td>
      <td>${contactNumber}</td>
      <td>${lastDonationDate.toLocaleDateString('en-US')}</td>
      <td>
      <div class="d-flex gap-1">
        <button id="edit-donor-btn" data-donor-id=${lastDonorId+1} type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#donor-modal"><img id="edit-donor-icon" data-donor-id=${lastDonorId+1} src="./assets/icons/pencil-square.svg" alt=""></button> 
        <button id="delete-donor-btn" data-donor-id=${lastDonorId+1} type="button" class="btn btn-danger btn-sm"><img id="delete-donor-icon" data-donor-id=${lastDonorId+1} src="./assets/icons/trash-can.svg" alt="delete icon"></button>
        </div>
      </td>
    </tr>
  `

    tableBody.insertAdjacentHTML("beforeend",tableRow) // Insert New Row
  } 

    const modal=bootstrap.Modal.getOrCreateInstance(donorModal); // Create a new Modal instance
    modal.hide(); // Close the modal

  }
}

const deleteDonor=(id)=>{
  const isConfirmed=confirm("Are You Sure?");
  if(isConfirmed){
   const toBeDeletedRow=document.querySelector(`[data-row-number="${id}"]`)
   toBeDeletedRow.remove()
  }
}

const resetForm=()=>{
  modalTitle.textContent="Add Donor"
  donorForm.removeAttribute("data-donor-id")
  bloodTypeSelect.value=""
  donorNameInput.value=""
  contactNumberInput.value=""
  ageInput.value=""
  lastDonationDateInput.value=""
}


const performActions=(e)=>{
if(e.target.dataset.donorId!==undefined){
  if(e.target.id==="edit-donor-btn" || e.target.id==="edit-donor-icon"){
    const selectedRow=document.querySelector(`[data-row-number="${e.target.dataset.donorId}"]`)
    const editedDonorDataArray=selectedRow.innerText.split("\t")
    editedDonorDataArray.pop()
    editedDonorDataArray.shift()

    modalTitle.textContent="Edit Donor"
    donorNameInput.value=editedDonorDataArray[0]
    ageInput.value=editedDonorDataArray[1]
    bloodTypeSelect.value=editedDonorDataArray[2]
    contactNumberInput.value=editedDonorDataArray[3]
    lastDonationDateInput.value=formatDateToYYYYMMDD(new Date(editedDonorDataArray[4]))
    donorForm.setAttribute("data-donor-id",e.target.dataset.donorId);
  }
  else {
    deleteDonor(e.target.dataset.donorId)
  }
}
}

const filterAndRenderTableRows=async (e)=>{
  e.preventDefault()
  const donorList=await fetchDonorData()


const formData=new FormData(e.target)
const searchValue=formData.get("search")

if(searchValue===""){
  renderTableRows()
  return
}

const result=donorList.filter((row)=> {
  const regex = new RegExp(searchValue, "i");
const isMatch = regex.test(row.donorName);

return isMatch
})

if(result.length===0) {
  renderTableRows()  
}
else {
  renderTableRows(result)
}


}


// EXECUTION
renderTableRows()

addDonorBtn.addEventListener('click',resetForm)
donorForm.addEventListener('submit',submitDonor)
searchForm.addEventListener('submit',filterAndRenderTableRows)
tableBody.addEventListener('click',performActions)


