import { API_URL } from "./config.js";

function createOption(
  value,
  text,
  { disabled = false, selected = false } = {}
) {
  const option = document.createElement("option");
  option.value = value;
  option.textContent = text;
  option.disabled = disabled;
  option.selected = selected;
  return option;
}

function addTelIDOptions(selectTelID, start, end) {
  for (let i = start; i <= end; i++) {
    selectTelID.appendChild(createOption(i, i));
  }
}

function populateLSTs(selectTelID) {
  addTelIDOptions(selectTelID, 1, 4);
}

function populateMSTs(selectTelID, site) {
  if (site === "North") {
    addTelIDOptions(selectTelID, 5, 59);
  } else if (site === "South") {
    addTelIDOptions(selectTelID, 5, 29);
    addTelIDOptions(selectTelID, 100, 130);
  }
}

function populateSSTs(selectTelID, site) {
  if (site === "South") {
    addTelIDOptions(selectTelID, 30, 99);
    addTelIDOptions(selectTelID, 131, 179);
  }
}

function populateTelIDOptions(selectTelID, site, telType) {
  // Remove current options
  selectTelID.innerHTML = "";
  selectTelID.appendChild(
    createOption("0", "select a Tel ID", {
      disabled: true,
      selected: true,
    })
  );

  if (site !== "North" && site !== "South") {
    return;
  }

  switch (telType) {
    case "LSTs":
      populateLSTs(selectTelID);
      break;
    case "MSTs":
      populateMSTs(selectTelID, site);
      break;
    case "SSTs":
      populateSSTs(selectTelID, site);
      break;
    default:
      break;
  }
}

function populateOBOptions(selectOB, obs) {
  // Clear old options
  selectOB.innerHTML = "";
  if (!obs.length) {
    selectOB.appendChild(
      createOption("0", "No OBs available", {
        disabled: true,
        selected: true,
      })
    );
    return "No OBs available";
  }
  selectOB.appendChild(
    createOption("0", "Select an OB", {
      disabled: true,
      selected: true,
    })
  );
  obs.forEach((ob) => selectOB.appendChild(createOption(ob, ob)));
  return "Select an OB";
}

export function setupSidebarAndFooter(window, document) {
  // Wait for DOMContentLoaded to ensure elements are present
  document.addEventListener("DOMContentLoaded", async function () {
    // Set up event listeners for mouse enter/leave sidebar
    const SIDEBAR_EL = document.getElementById("wrapper");
    const sidebarWrapper = document.getElementById("sidebar-wrapper");
    sidebarWrapper.addEventListener("mouseenter", () =>
      SIDEBAR_EL.classList.remove("collapsed")
    );
    sidebarWrapper.addEventListener("mouseleave", () =>
      SIDEBAR_EL.classList.add("collapsed")
    );

    // Datepicker initialization
    $("#date-picker").datepicker({
      format: "yyyy-mm-dd",
      autoclose: true,
      todayHighlight: true,
      todayBtn: true,
      clearBtn: true,
      calendarWeeks: true,
      orientation: "right",
    });

    function handleDatepickerMouseEnter() {
      SIDEBAR_EL.classList.remove("collapsed");
    }

    function handleDatepickerMouseLeave() {
      SIDEBAR_EL.classList.add("collapsed");
    }

    function attachDatepickerSidebarEvents() {
      const datepickerDiv = document.querySelector(
        ".datepicker.datepicker-dropdown"
      );
      if (datepickerDiv) {
        datepickerDiv.addEventListener(
          "mouseenter",
          handleDatepickerMouseEnter
        );
        datepickerDiv.addEventListener(
          "mouseleave",
          handleDatepickerMouseLeave
        );
      }
    }

    $("#date-picker").on("show", function () {
      // Wait until datepicker is actually in the DOM
      setTimeout(attachDatepickerSidebarEvents, 0);
    });

    let dateOBs = {};
    // Fetch the OB-Date mapping from the JSON file
    // It is used to populate the OB dropdown based on the selected date
    $.getJSON(`${API_URL}/v1/ob_date_map`, function (data) {
      dateOBs = data;
    }).fail(function () {
      console.error("Failed to load /data/v1/ob_date_map.json");
    });

    const path = window.location.pathname; // e.g. "/LSTs/pointings"
    const arrayElement = path.split("/").filter(Boolean)[0];
    const validTelTypes = ["LSTs", "MSTs", "SSTs"];
    const isTelescopeElement = validTelTypes.includes(arrayElement);

    // sidebar elements
    const selectSite = document.getElementById("which-Site");
    // footer elements
    const footerSite = document.getElementById("footer-site");
    const footerDate = document.getElementById("footer-date");
    // Set up starting value
    footerSite.textContent = selectSite.value;

    if (isTelescopeElement) {
      // sidebar elements
      const selectTelID = document.getElementById("which-Tel-ID");
      // footer elements
      const footerTelType = document.getElementById("footer-tel-type");
      const footerTelID = document.getElementById("footer-tel-id");
      // Set up starting value
      footerTelType.textContent = arrayElement;

      selectSite.addEventListener("change", function () {
        populateTelIDOptions(selectTelID, selectSite.value, arrayElement);
        footerSite.textContent = selectSite.value;
      });

      selectTelID.addEventListener("change", function () {
        footerTelID.textContent = selectTelID.value;
        footerTelID.style.color = ""; // Remove any inline color style (including red)
      });
    } else {
      selectSite.addEventListener("change", function () {
        footerSite.textContent = selectSite.value;
      });
    }
    // sidebar elements
    const selectOB = document.getElementById("which-OB");
    // footer elements
    const footerOB = document.getElementById("footer-ob");

    if (selectOB) {
      selectOB.addEventListener("change", function () {
        footerOB.textContent = selectOB.value;
        footerOB.style.color = ""; // Remove any inline color style (including red)
      });
    }

    // Datepicker change event to update footer date and OB dropdown
    $("#date-picker").on("changeDate", function () {
      const selectedDate = $("#date-picker").val();
      footerDate.textContent = selectedDate;
      footerDate.style.color = ""; // Remove any inline color style (including red)

      // If we remove the OB in the sidebar the following part should be revised
      if (isTelescopeElement) {
        const obs = dateOBs[selectedDate] || [];
        const firstOB = populateOBOptions(selectOB, obs);
        footerOB.textContent = firstOB;
        footerOB.style.color = "red";
      }
    });

    const buttonMakePlot = document.getElementById("makePlot");
    if (buttonMakePlot) {
      const { makePlot } = await import("./plot.js");
      buttonMakePlot.addEventListener("click", makePlot);
    }

    // Initial trigger
    selectSite.dispatchEvent(new Event("change"));
  });
}

if (typeof window !== "undefined" && typeof document !== "undefined") {
  setupSidebarAndFooter(window, document);
}
