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

const addBloodBtn=document.querySelector("#add-blood-btn");
const bloodForm=document.querySelector("#blood-form");

const bloodModal=document.querySelector("#blood-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 quantityInput=document.querySelector("#quantity");

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


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

const renderTableRows=async (bloodArray)=>{
let bloodList;
if(!bloodArray)
  bloodList=await fetchBloodData()
else {
  bloodList=[...bloodArray]
}

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

  tableBody.innerHTML=tableRows
}
}

const submitBlood=(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 quantity = formData.get("quantity");

 if(bloodType!=="" && quantity!==""){
  // EDIT BLOOD IF ID EXISTS ON FORM
  if(e.target.dataset.bloodId) {
    const selectedRow=document.querySelector(`[data-row-number="${e.target.dataset.bloodId}"]`)
 
    selectedRow.innerHTML=`<th scope="row">${e.target.dataset.bloodId}</th>
    <td>${bloodType}</td>
    <td>${donorName}</td>
    <td>${contactNumber}</td>
    <td>${quantity}ml</td>
    <td>
    <div class="d-flex gap-1">
      <button id="edit-blood-btn" data-blood-id=${e.target.dataset.bloodId} type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#blood-modal"><img id="edit-blood-icon" data-blood-id=${e.target.dataset.bloodId} src="./assets/icons/pencil-square.svg" alt=""></button> 
      <button id="delete-blood-btn" data-blood-id=${e.target.dataset.bloodId} type="button" class="btn btn-danger btn-sm"><img id="delete-blood-icon" data-blood-id=${e.target.dataset.bloodId} 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 lastBloodId=Number(allRows[allRows.length-1].getAttribute("data-row-number"))
  const tableRow=
  `<tr id="row" data-row-number=${lastBloodId+1}>
      <th scope="row">${lastBloodId+1}</th>
      <td>${bloodType}</td>
      <td>${donorName}</td>
      <td>${contactNumber}</td>
      <td>${quantity}ml</td>
      <td>
      <div class="d-flex gap-1">
        <button id="edit-blood-btn" data-blood-id=${lastBloodId+1} type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#blood-modal"><img id="edit-blood-icon" data-blood-id=${lastBloodId+1} src="./assets/icons/pencil-square.svg" alt=""></button> 
        <button id="delete-blood-btn" data-blood-id=${lastBloodId+1} type="button" class="btn btn-danger btn-sm"><img id="delete-blood-icon" data-blood-id=${lastBloodId+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(bloodModal); // Create a new Modal instance
    modal.hide(); // Close the modal

  }
}

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

const resetForm=()=>{
  modalTitle.textContent="Add Blood"
  bloodForm.removeAttribute("data-blood-id")
  bloodTypeSelect.value=""
  donorNameInput.value=""
  contactNumberInput.value=""
  quantityInput.value=""

}


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

    modalTitle.textContent="Edit Blood"
    bloodTypeSelect.value=editedBloodDataArray[0]
    donorNameInput.value=editedBloodDataArray[1]
    contactNumberInput.value=editedBloodDataArray[2]
    quantityInput.value=editedBloodDataArray[3].slice(0,-2) // remove ml from data
    bloodForm.setAttribute("data-blood-id",e.target.dataset.bloodId);
  }
  else {
    deleteBlood(e.target.dataset.bloodId)
  }
}
}

const filterAndRenderTableRows=async (e)=>{
  e.preventDefault()
  const bloodList=await fetchBloodData()


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

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

const result=bloodList.filter((row)=> row.bloodType===searchValue.toUpperCase())

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


}

// EXECUTION
renderTableRows()

addBloodBtn.addEventListener('click',resetForm)
bloodForm.addEventListener('submit',submitBlood)
searchForm.addEventListener('submit',filterAndRenderTableRows)
tableBody.addEventListener('click',performActions)


