import { deleteVisitReport, getPatients, getSession, getVisitReport, saveVisitReport } from "./api.js";

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

const visitDetailTitle = document.getElementById("visitDetailTitle");
const visitDetailMeta = document.getElementById("visitDetailMeta");
const visitDetailContent = document.getElementById("visitDetailContent");
const addVisitRowBtn = document.getElementById("addVisitRowBtn");
const deleteVisitBtn = document.getElementById("deleteVisitBtn");
const saveVisitBtn = document.getElementById("saveVisitBtn");

let activeReport = null;
let reportItems = [];
let patientNames = [];
let activeReportId = reportId;

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

function formatDateTime(value) {
  const date = new Date(String(value ?? "").replace(" ", "T"));
  if (Number.isNaN(date.getTime())) return value || "-";

  return new Intl.DateTimeFormat("tr-TR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric"
  }).format(date).replaceAll(".", " / ");
}

function createEmptyRow() {
  return {
    id: `new-${Date.now()}-${Math.random().toString(16).slice(2)}`,
    patientName: "",
    diagnosis: "",
    treatment: ""
  };
}

function syncHeader() {
  visitDetailTitle.textContent = activeReportId ? `Vizit • ${formatDateTime(activeReport?.createdAt || "")}` : "Yeni Vizit";
  visitDetailMeta.innerHTML = activeReportId
    ? `
      <span>Oluşturulma: ${escapeHtml(formatDateTime(activeReport?.createdAt || ""))}</span>
      <span>Güncelleme: ${escapeHtml(formatDateTime(activeReport?.updatedAt || ""))}</span>
      <span>Kullanıcı: ${escapeHtml(activeReport?.updatedByUsername || "-")}</span>
    `
    : '<span>Yeni vizit tablosu</span>';
  deleteVisitBtn.classList.toggle("hidden", !activeReportId);
}

function renderPage() {
  const rows = reportItems.length ? reportItems : [createEmptyRow()];
  const optionsMarkup = patientNames.map((name) => `<option value="${escapeHtml(name)}"></option>`).join("");

  visitDetailContent.innerHTML = `
    <section class="orders-layout">
      <article class="panel-card orders-sheet visit-sheet">
        <div class="orders-summary visit-summary">
          <p><strong>Vizit Tarihi:</strong> ${escapeHtml(formatDateTime(activeReport?.createdAt || new Date().toISOString()))}</p>
          <p><strong>Son Düzenleme:</strong> ${escapeHtml(formatDateTime(activeReport?.updatedAt || new Date().toISOString()))}</p>
          <p><strong>Kullanıcı:</strong> ${escapeHtml(activeReport?.updatedByUsername || "-")}</p>
        </div>

        <datalist id="visitPatientNamesList">${optionsMarkup}</datalist>

        <div class="orders-table-wrap">
          <table class="orders-table visit-table">
            <thead>
              <tr>
                <th>Ad Soyad</th>
                <th>Teşhis</th>
                <th>Tedavi</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              ${rows.map((item, index) => `
                <tr data-visit-row="${escapeHtml(String(item.id || index))}">
                  <td>
                    <input data-key="patientName" type="text" list="visitPatientNamesList" class="visit-patient-name-input" value="${escapeHtml(item.patientName || "")}" />
                  </td>
                  <td><textarea data-key="diagnosis" rows="3">${escapeHtml(item.diagnosis || "")}</textarea></td>
                  <td><textarea data-key="treatment" rows="3">${escapeHtml(item.treatment || "")}</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>
  `;

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

function collectRows() {
  return Array.from(visitDetailContent.querySelectorAll("tbody tr")).map((row) => ({
    patientName: row.querySelector('[data-key="patientName"]')?.value?.trim() || "",
    diagnosis: row.querySelector('[data-key="diagnosis"]')?.value?.trim() || "",
    treatment: row.querySelector('[data-key="treatment"]')?.value?.trim() || ""
  }));
}

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

  if (activeReportId) {
    try {
      const data = await getVisitReport(activeReportId);
      activeReport = data.report;
      reportItems = data.items || [];
      patientNames = data.patientNames || [];
    } catch (error) {
      visitDetailContent.innerHTML = `<section class="panel-card"><p class="empty-state">${escapeHtml(error.message)}</p></section>`;
      return;
    }
  } else {
    patientNames = [];
  }

  if (!patientNames.length) {
    try {
      const patients = await getPatients();
      patientNames = Array.isArray(patients) ? patients.map((patient) => patient.fullName).filter(Boolean) : [];
    } catch {
      patientNames = [];
    }
  }

  syncHeader();
  renderPage();

  addVisitRowBtn?.addEventListener("click", () => {
    reportItems = collectRows();
    reportItems.push(createEmptyRow());
    renderPage();
  });

  saveVisitBtn?.addEventListener("click", async () => {
    try {
      const response = await saveVisitReport(activeReportId, collectRows());
      activeReport = response.savedReport?.report || activeReport;
      reportItems = response.savedReport?.items || [];
      activeReportId = Number(activeReport?.id || activeReportId || 0);
      if (!reportId && activeReportId) {
        window.history.replaceState({}, "", `visit-detail.php?id=${encodeURIComponent(activeReportId)}`);
      }
      syncHeader();
      renderPage();
      window.alert("Vizit kaydı kaydedildi.");
    } catch (error) {
      window.alert(error.message);
    }
  });

  deleteVisitBtn?.addEventListener("click", async () => {
    if (!activeReportId) return;
    if (!window.confirm("Bu vizit kaydını silmek istediğinize emin misiniz?")) return;

    try {
      await deleteVisitReport(activeReportId);
      window.location.replace("visits.php");
    } catch (error) {
      window.alert(error.message);
    }
  });
}

init();
