document.addEventListener("DOMContentLoaded", function () {
  const calculatorValidations = {
    gramLimit: {
      min: 1,
      max: 1000,
      elSelector: ".goldWeightRange",
    },
    monthLimit: {
      min: 1,
      max: 36,
      elSelector: ".creditPeriodRange",
    },
    creditAmount: {
      min: 1,
      max: 5000,
      elSelector: ".creditRangeLimit",
    },
  };

  const calculatorSettings = {
    goldPercentage: 18,
    goldHallMarks: [375, 583, 750, 875, 916, 999],
    hallmarkPrices: {
      375: 400,
      583: 64,
      750: 82,
      875: 96,
      916: 100,
      999: 510,
    },
    // for backend
    // hallmarkPrices: {},
  };

  const calculatorForm = document.querySelector("#loan-calculator-form");

  function getStructuredArrayData(form) {
    const data = {};
    new FormData(form).forEach((value, key) => {
      const path = key.match(/[^[\]]+/g);
      path.reduce((acc, field, index) => {
        if (index === path.length - 1) {
          acc[field] = value;
        } else {
          acc[field] = acc[field] || (isNaN(Number(path[index + 1])) ? {} : []);
          return acc[field];
        }
      }, data);
    });
    return data;
  }

  function showTabItems(targetName = undefined) {
    let tabTargetName =
      targetName ??
      document
        .querySelector("[data-tab-target].active")
        .getAttribute("data-tab-target");
    document.querySelectorAll(`[data-tab-name]`).forEach((el) => {
      const tabName = el.getAttribute("data-tab-name");
      el.classList.add("d-none");
      if (tabName == tabTargetName) {
        el.classList.remove("d-none");
      }
    });
  }

  function setTabEvents() {
    const tabTargetBtns = document.querySelectorAll("[data-tab-target]");
    tabTargetBtns.forEach((tabTargetBtn) => {
      tabTargetBtn.addEventListener("click", (ev) => {
        tabTargetBtns.forEach((btn) => btn.classList.remove("active"));
        ev.target.classList.add("active");
        let tabTargetName = ev.target.getAttribute("data-tab-target");
        showTabItems(tabTargetName);
      });
    });
  }

  function setGoldValidations() {
    const validations = Object.values(calculatorValidations);
    validations.forEach((validation) => {
      if (!validation.elSelector) return;
      const validationElements = document.querySelectorAll(
        validation.elSelector
      );
      validationElements.forEach((validationEl) => {
        validationEl.min = validation.min;
        validationEl.max = validation.max;
        validationEl.value = validation.min;
      });
    });
  }

  function setUnitInputRanges(unitRangeInputs) {
    unitRangeInputs.forEach((unitInput) => {
      unitInput.value = unitInput.min;
      const updateLabelValue = (unitInp) => {
        const unitLabelValue =
          unitInp.parentElement.querySelector(".range-input-value");
        const unitNameElement =
          unitInp.parentElement.querySelector(".unit-name");
        unitLabelValue.value = unitInp.value;
        unitNameElement.innerText = unitInp.getAttribute("data-unit");
        adjustInputWidth(unitLabelValue);
      };
      updateLabelValue(unitInput);

      unitInput.addEventListener("input", (ev) => {
        const unitLabelValue =
          ev.target.parentElement.querySelector(".range-input-value");
        if (ev.target.value === "") {
          unitLabelValue.value = "";
        } else {
          let value = parseFloat(ev.target.value);
          if (!isNaN(value)) {
            if (value > unitInput.max) {
              value = unitInput.max;
            }
            unitLabelValue.value = value;
            unitInput.value = value;
            adjustInputWidth(unitLabelValue);
            updateRangeBackground(unitInput);
            calculateTerms();
          }
        }
      });

      const unitLabelValue =
        unitInput.parentElement.querySelector(".range-input-value");

      unitLabelValue.addEventListener("input", () => {
        if (unitLabelValue.value === "") return;
        let value = parseFloat(unitLabelValue.value);
        if (!isNaN(value)) {
          if (value > unitInput.max) {
            value = unitInput.max;
          }
          unitInput.value = value;
          adjustInputWidth(unitLabelValue);
          updateLabelValue(unitInput);
          updateRangeBackground(unitInput);
          calculateTerms();
        }
      });

      unitLabelValue.addEventListener("blur", () => {
        let value = parseFloat(unitLabelValue.value);
        if (isNaN(value) || value < unitInput.min) {
          value = unitInput.min;
        }
        unitInput.value = value;
        adjustInputWidth(unitLabelValue);
        updateLabelValue(unitInput);
        updateRangeBackground(unitInput);
        calculateTerms();
      });
    });
  }

  function adjustInputWidth(input) {
    input.style.width = `${input.value.length + 1}ch`;
  }

  function updateRangeBackground(rangeInput) {
    const value =
      ((rangeInput.value - rangeInput.min) /
        (rangeInput.max - rangeInput.min)) *
      100;
    rangeInput.style.background = `linear-gradient(to right, var(--brand-color-blue-dark) ${value}%, var(--main-color-white) ${value}%)`;
  }

  function showGoldHallMarks() {
    const goldHallMarkListElements = document.querySelectorAll(
      ".gold-hallmark-value"
    );

    const setHallMarkList = (hallMarkListEl, elIndex) => {
      hallMarkListEl.innerHTML = "";
      calculatorSettings.goldHallMarks.forEach((hallMark, i) => {
        const price = calculatorSettings.hallmarkPrices[hallMark];
        const inputName = hallMarkListEl.getAttribute("data-form-name");
        const labelIdName = `gold-hallmark-${hallMark}__${elIndex}${i}`;

        hallMarkListEl.innerHTML += `
          <input type="radio" class="hallmark-input" name="${inputName}" value="${price}" ${
          i == 0 ? "checked" : ""
        } id="${labelIdName}" />
          <label for="${labelIdName}">${hallMark}</label>
        `;
      });
    };

    goldHallMarkListElements.forEach(setHallMarkList);
  }

  function setHallMarkEvent() {
    document
      .querySelectorAll(".gold-hallmark-value input")
      .forEach((inp) => inp.addEventListener("change", calculateTerms));
  }

  function calculateMonthlyPayment(creditPeriod, totalAmount) {
    const monthlyInterestRate = calculatorSettings.goldPercentage / 12 / 100;
    const compoundedRate = (1 + monthlyInterestRate) ** creditPeriod;
    const monthlyPayment =
      ((monthlyInterestRate * compoundedRate) / (compoundedRate - 1)) *
      totalAmount;
    return monthlyPayment;
  }

  function calculateTerms() {
    setHallMarkEvent();

    const calculatorData = getStructuredArrayData(calculatorForm);

    // hallmarkTab hesablamaları
    const hallmarkTabData = calculatorData.data.hallmarkTab;
    let goldTermMonthlyPaymentEl = document.querySelector(
      "#goldTerms .monthly-payment span"
    );
    let loanAmountEl = document.getElementById("loanAmount");
    let totalLoanAmount = 0;
    let amountMonthly = 0;

    hallmarkTabData.forEach((data) => {
      const hallmarkValue = parseFloat(data.hallmark); // seçilən qiymət
      const goldWeight = parseFloat(data.goldWeight);
      const creditPeriod = parseFloat(data.creditPeriod);

      const loanAmount = hallmarkValue * goldWeight;
      totalLoanAmount += loanAmount;
      amountMonthly += calculateMonthlyPayment(creditPeriod, loanAmount);
    });
    goldTermMonthlyPaymentEl.innerText = amountMonthly.toFixed(2);
    loanAmountEl.innerText = totalLoanAmount.toFixed(2);

    // priceTab hesablamaları
    const priceTabData = calculatorData.data.priceTab;
    if (priceTabData) {
      let priceTermMonthlyPaymentEl = document.querySelector(
        "#priceTerms .monthly-payment span"
      );
      let goldWeightEl = document.querySelector("#priceTerms .goldWeight");
      const creditAmount = parseFloat(priceTabData.creditAmount);
      const creditPeriod = parseFloat(priceTabData.creditPeriod);
      const hallmarkValue = parseFloat(priceTabData.hallmark);
      if (hallmarkValue && creditAmount && creditPeriod) {
        priceTermMonthlyPaymentEl.innerText = calculateMonthlyPayment(
          creditPeriod,
          creditAmount
        ).toFixed(2);
        goldWeightEl.innerText = parseFloat(
          creditAmount / hallmarkValue
        ).toFixed(3);
      }
    }
  }

  let currentHallMarkIndex = 1;

  function createCalculatorItemBtn() {
    const removeBtnNode = document.createElement("button");
    removeBtnNode.classList.add("btn");
    removeBtnNode.type = "button";
    removeBtnNode.classList.add("btn-link");
    removeBtnNode.appendChild(document.createTextNode("Sil"));
    removeBtnNode.addEventListener("click", () => {
      currentHallMarkIndex--;
      const parentEl = removeBtnNode.closest(".calculator-item");
      // remove divider
      parentEl.previousElementSibling.remove();
      parentEl.remove();
      calculateTerms();
    });
    return removeBtnNode;
  }

  function addMoreHallMarkItem() {
    const addCalculatorItemBtn = document.querySelector(".add-other-loan-btn");

    const changeInputName = (inp, index) => {
      inp.setAttribute(
        "name",
        inp.name.replace("[0]", `[${currentHallMarkIndex}]`)
      );
      inp.checked = index == 0 ? true : false;
      const nextLabel = inp.nextElementSibling;
      if (!nextLabel && nextLabel?.nodeName != "LABEL") return;
      const hallmarkLabelId = `${inp.id}_${currentHallMarkIndex}`;
      inp.setAttribute("id", hallmarkLabelId);
      nextLabel.setAttribute("for", hallmarkLabelId);
    };

    const handleMore = () => {
      let clonedCalculatorItem = document
        .querySelector(".calculator-item")
        .cloneNode(true);
      clonedCalculatorItem
        .querySelector(".gold-hallmark-title")
        .appendChild(createCalculatorItemBtn());
      clonedCalculatorItem.setAttribute("data-tab-name", "hallmarkTab");
      clonedCalculatorItem.classList.add("mt-4");

      clonedCalculatorItem.querySelectorAll("input").forEach(changeInputName);
      addCalculatorItemBtn.insertAdjacentElement(
        "beforebegin",
        clonedCalculatorItem
      );
      clonedCalculatorItem.insertAdjacentHTML(
        "beforebegin",
        `
                <div class="divider"></div>
            `
      );

      setUnitInputRanges(clonedCalculatorItem.querySelectorAll("[data-unit]"));
      calculateTerms();
      currentHallMarkIndex++;
    };

    addCalculatorItemBtn.addEventListener("click", handleMore);
  }

  // this codes for backend
  function handleCalculatorFormSubmit() {
    const calculatorData = getStructuredArrayData(calculatorForm);
    const creditModalForm = document.querySelector("#applyCreditModal form");
    creditModalForm.addEventListener("submit", function (e) {
      e.preventDefault();
      console.log("sending .....");
      console.log(calculatorData);
    });
  }

  document.querySelectorAll('input[type="range"]').forEach((input) => {
    input.addEventListener("input", function () {
      updateRangeBackground(this);
    });

    // Trigger the input event initially to set the correct background
    updateRangeBackground(input);
  });

  // the inputs gets focused on click
  document.querySelectorAll(".range-input-value-box").forEach((box) => {
    box.addEventListener("click", function () {
      const input = this.querySelector(".range-input-value");
      if (input) {
        input.focus();
      }
    });
  });

  showTabItems();
  setTabEvents();
  setGoldValidations();
  showGoldHallMarks();
  setUnitInputRanges(document.querySelectorAll("[data-unit]"));
  calculateTerms();
  addMoreHallMarkItem();
  handleCalculatorFormSubmit();

  // this function take priceData from Backend
  /*
  async function fetchHallmarkPrices() {
    try {
      const response = await fetch('/api/hallmark-prices'); 
      const data = await response.json();
      calculatorSettings.hallmarkPrices = data;
    } catch (error) {
      console.error('error when take data:', error);
    }
  }

  // set data each function
  // fetchHallmarkPrices().then(() => {
  //   showGoldHallMarks();
  //   calculateTerms();
  // });
  */
});
