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

const params = new URLSearchParams(window.location.search);
const slug = params.get("slug");
const formId = Number(params.get("formId") || 0);

const ordersBackLink = document.getElementById("ordersBackLink");
const ordersTitle = document.getElementById("ordersTitle");
const ordersContent = document.getElementById("ordersContent");
const pasteOrdersBtn = document.getElementById("pasteOrdersBtn");
const ordersPasteCard = document.getElementById("ordersPasteCard");
const ordersPasteInput = document.getElementById("ordersPasteInput");
const applyOrdersPasteBtn = document.getElementById("applyOrdersPasteBtn");
const cancelOrdersPasteBtn = document.getElementById("cancelOrdersPasteBtn");
const addOrderRowBtn = document.getElementById("addOrderRowBtn");
const printOrdersBtn = document.getElementById("printOrdersBtn");
const saveOrdersBtn = document.getElementById("saveOrdersBtn");

let activePatient = null;
let orderItems = [];
let activeFormId = formId;

function togglePasteCard(force) {
  const willShow = typeof force === "boolean" ? force : ordersPasteCard.classList.contains("hidden");
  ordersPasteCard.classList.toggle("hidden", !willShow);
  if (willShow) {
    ordersPasteInput.focus();
  } else {
    ordersPasteInput.value = "";
  }
}

function escapeHtml(value) {
  return String(value ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;");
}

function formatDate(value) {
  const text = String(value ?? "").trim();
  if (!text) return "-";
  const date = new Date(text);
  if (Number.isNaN(date.getTime())) return text;
  return date.toLocaleDateString("tr-TR").replaceAll(".", ".");
}

function createEmptyRow() {
  return {
    id: `new-${Date.now()}-${Math.random().toString(16).slice(2)}`,
    infoText: "",
    medicineName: "",
    applicationDose: "",
    usageHours: ""
  };
}

function splitPastedLine(line) {
  if (line.includes("\t")) {
    return line.split("\t");
  }

  if (line.includes(";")) {
    return line.split(";");
  }

  if (line.includes(",")) {
    return line.split(",");
  }

  return [line];
}

function parsePastedOrders(text) {
  return String(text ?? "")
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => {
      const parts = splitPastedLine(line).map((part) => String(part ?? "").trim());
      const normalizedParts = [...parts];
      while (normalizedParts.length < 4) normalizedParts.push("");

      const looksLikeOldOrder =
        normalizedParts.length >= 4
        && normalizedParts[0] !== ""
        && normalizedParts[1] !== ""
        && normalizedParts[2] !== ""
        && normalizedParts[3] !== "";

      return {
        id: `paste-${Date.now()}-${Math.random().toString(16).slice(2)}`,
        medicineName: looksLikeOldOrder ? normalizedParts[0] : normalizedParts[0],
        applicationDose: looksLikeOldOrder ? normalizedParts[1] : normalizedParts[1],
        usageHours: looksLikeOldOrder ? normalizedParts[2] : normalizedParts[2],
        infoText: looksLikeOldOrder ? normalizedParts.slice(3).join(" | ") : normalizedParts.slice(3).join(" | ")
      };
    })
    .filter((row) => row.infoText || row.medicineName || row.applicationDose || row.usageHours);
}

function syncHeader() {
  ordersTitle.textContent = activeFormId ? `${activePatient?.fullName || "Order"} • Düzenle` : `${activePatient?.fullName || "Order"} • Yeni`;
  ordersBackLink.href = `detail.php?slug=${encodeURIComponent(slug || "")}`;
}

function renderPage() {
  const rows = orderItems.length ? orderItems : [createEmptyRow()];

  ordersContent.innerHTML = `
    <section class="orders-layout">
      <article class="panel-card orders-sheet">
        <div class="orders-print-logo-wrap">
          <img class="orders-print-logo" src="assets/omur-logo.jpg" alt="Ömür Huzurevi logosu" />
        </div>
        <div class="orders-summary">
          <p><strong>Yaşlı Adı – Soyadı:</strong> ${escapeHtml(activePatient?.fullName || "-")}</p>
          <p><strong>T.C. Kimlik No:</strong> ${escapeHtml(activePatient?.identityNumber || "-")}</p>
          <p><strong>Doğum Tarihi:</strong> ${escapeHtml(formatDate(activePatient?.birthDate || ""))}</p>
          <p><strong>Kronik Rahatsızlıkları:</strong> ${escapeHtml(activePatient?.diagnosis || "-")}</p>
        </div>

        <div class="orders-table-wrap">
          <table class="orders-table">
            <thead>
              <tr>
                <th>İlaç Adı</th>
                <th>Uygulama Dozu</th>
                <th>Kullanım Saatleri</th>
                <th>Bilgilendirme</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              ${rows
                .map(
                  (item, index) => `
                    <tr data-order-row="${escapeHtml(String(item.id || index))}">
                      <td><textarea data-key="medicineName" rows="2">${escapeHtml(item.medicineName || "")}</textarea></td>
                      <td><textarea data-key="applicationDose" rows="2">${escapeHtml(item.applicationDose || "")}</textarea></td>
                      <td><textarea data-key="usageHours" rows="2">${escapeHtml(item.usageHours || "")}</textarea></td>
                      <td><textarea data-key="infoText" rows="2">${escapeHtml(item.infoText || "")}</textarea></td>
                      <td class="orders-table-actions">
                        <button class="file-action-btn file-action-btn-danger" type="button" data-remove-row="${index}" aria-label="Satırı sil">×</button>
                      </td>
                    </tr>
                  `
                )
                .join("")}
            </tbody>
          </table>
        </div>
      </article>
    </section>
  `;

  ordersContent.querySelectorAll("[data-remove-row]").forEach((button) => {
    button.addEventListener("click", () => {
      const index = Number(button.dataset.removeRow);
      orderItems = orderItems.filter((_, itemIndex) => itemIndex !== index);
      renderPage();
    });
  });
}

function collectRows() {
  return Array.from(ordersContent.querySelectorAll("tbody tr")).map((row) => ({
    infoText: row.querySelector('[data-key="infoText"]')?.value?.trim() || "",
    medicineName: row.querySelector('[data-key="medicineName"]')?.value?.trim() || "",
    applicationDose: row.querySelector('[data-key="applicationDose"]')?.value?.trim() || "",
    usageHours: row.querySelector('[data-key="usageHours"]')?.value?.trim() || ""
  }));
}

async function init() {
  try {
    const session = await getSession();
    if (!session.authenticated) {
      window.location.replace("index.php");
      return;
    }
  } catch {
    ordersContent.innerHTML = '<section class="panel-card"><p class="empty-state">Sunucu bağlantısı kurulamadı.</p></section>';
    return;
  }

  if (!slug) {
    ordersContent.innerHTML = '<section class="panel-card"><p class="empty-state">Hasta bilgisi bulunamadı.</p></section>';
    return;
  }

  try {
    const data = await getOrdersBySlug(slug, activeFormId);
    activePatient = data.patient;
    orderItems = data.activeOrder?.items || [];
    syncHeader();
    renderPage();
  } catch (error) {
    ordersContent.innerHTML = `<section class="panel-card"><p class="empty-state">${escapeHtml(error.message)}</p></section>`;
    return;
  }

  addOrderRowBtn.addEventListener("click", () => {
    orderItems = collectRows();
    orderItems.push(createEmptyRow());
    renderPage();
  });

  pasteOrdersBtn.addEventListener("click", () => {
    togglePasteCard();
  });

  cancelOrdersPasteBtn.addEventListener("click", () => {
    togglePasteCard(false);
  });

  applyOrdersPasteBtn.addEventListener("click", () => {
    const pastedRows = parsePastedOrders(ordersPasteInput.value);
    if (!pastedRows.length) {
      window.alert("Yapıştırılan veride aktarılacak satır bulunamadı.");
      return;
    }

    orderItems = [...collectRows().filter((row) => row.infoText || row.medicineName || row.applicationDose || row.usageHours), ...pastedRows];
    renderPage();
    togglePasteCard(false);
  });

  printOrdersBtn.addEventListener("click", () => {
    window.print();
  });

  saveOrdersBtn.addEventListener("click", async () => {
    if (!activePatient) return;

    try {
      const response = await saveOrders(activePatient.id, collectRows(), activeFormId);
      activeFormId = Number(response.savedOrder?.form?.id || activeFormId || 0);
      orderItems = response.savedOrder?.items || [];
      renderPage();
      window.alert("Orders bilgileri kaydedildi.");
    } catch (error) {
      window.alert(error.message);
    }
  });
}

init();
