import { createPatient, getSession } from "./api.js";

const addPatientForm = document.getElementById("addPatientForm");
const addPatientMessage = document.getElementById("addPatientMessage");
const prescribedMedicationsRows = document.getElementById("prescribedMedicationsRows");
const addMedicationRowBtn = document.getElementById("addMedicationRowBtn");

function showMessage(message, isError = false) {
  addPatientMessage.textContent = message;
  addPatientMessage.classList.remove("hidden", "error-text");
  addPatientMessage.classList.add(isError ? "error-text" : "helper-text");
}

function getMissingImportantFields(formData) {
  const fields = [
    { key: "identityNumber", label: "Kimlik Numarası" },
    { key: "birthDate", label: "Doğum Tarihi" },
    { key: "status", label: "Durum" },
    { key: "roomNumber", label: "Oda" }
  ];

  return fields.filter(({ key }) => !String(formData.get(key) ?? "").trim());
}

function createMedicationRow(item = {}) {
  const row = document.createElement("div");
  row.className = "prescribed-medication-row";
  row.innerHTML = `
    <textarea class="prescribed-medication-name" rows="2" placeholder="İlaç adı">${String(item.name ?? "")}</textarea>
    <input class="prescribed-medication-expiry" type="date" value="${String(item.expiryDate ?? "")}" />
    <button class="file-action-btn file-action-btn-danger" type="button" aria-label="İlaç satırını sil">×</button>
  `;

  row.querySelector(".file-action-btn-danger")?.addEventListener("click", () => {
    row.remove();
    if (!prescribedMedicationsRows.children.length) {
      prescribedMedicationsRows.appendChild(createMedicationRow());
    }
  });

  return row;
}

function collectMedicationRows() {
  return Array.from(prescribedMedicationsRows.querySelectorAll(".prescribed-medication-row")).map((row) => ({
    name: row.querySelector(".prescribed-medication-name")?.value?.trim() || "",
    expiryDate: row.querySelector(".prescribed-medication-expiry")?.value || ""
  })).filter((item) => item.name || item.expiryDate);
}

async function init() {
  try {
    const session = await getSession();

    if (!session.authenticated) {
      window.location.replace("/index.php");
      return;
    }
  } catch {
    showMessage("Sunucu bağlantısı kurulamadı.", true);
    addPatientForm.classList.add("hidden");
    return;
  }

  prescribedMedicationsRows.appendChild(createMedicationRow());
  addMedicationRowBtn?.addEventListener("click", () => {
    prescribedMedicationsRows.appendChild(createMedicationRow());
  });

  addPatientForm.addEventListener("submit", async (event) => {
    event.preventDefault();
    const formData = new FormData(addPatientForm);

    try {
      formData.set("fullName", String(formData.get("fullName")).trim());
      formData.set("roomNumber", String(formData.get("roomNumber")).trim());
      formData.set("birthDate", String(formData.get("birthDate")).trim());
      formData.set("admissionDate", String(formData.get("admissionDate")).trim());
      formData.set("identityNumber", String(formData.get("identityNumber")).trim());
      formData.set("status", String(formData.get("status")).trim());
      formData.set("heightWeight", String(formData.get("heightWeight")).trim());
      formData.set("prescribedMedications", JSON.stringify(collectMedicationRows()));
      formData.set("medicationHours", String(formData.get("medicationHours")).trim());
      formData.set("diagnosis", String(formData.get("diagnosis")).trim());
      formData.set("emergencyContact", String(formData.get("emergencyContact")).trim());
      formData.set("notes", String(formData.get("notes")).trim());
      formData.set(
        "carePlan",
        String(formData.get("carePlan"))
          .split(",")
          .map((item) => item.trim())
          .filter(Boolean)
          .join(", ")
      );

      const missingFields = getMissingImportantFields(formData);
      if (missingFields.length) {
        const confirmed = window.confirm(
          `Şu bilgiler eksik: ${missingFields.map((field) => field.label).join(", ")}.\nYine de kaydetmek istiyor musunuz?`
        );
        if (!confirmed) {
          showMessage("Eksik bilgileri tamamlayıp tekrar kaydedebilirsiniz.", true);
          return;
        }
      }

      const patient = await createPatient(formData);

      showMessage("Hasta kaydı oluşturuldu. Detay sayfasına yönlendiriliyorsunuz.");
      window.setTimeout(() => {
        window.location.href = `detail.php?slug=${encodeURIComponent(patient.slug)}`;
      }, 600);
    } catch (error) {
      showMessage(error.message, true);
    }
  });
}

init();
