import { deletePatientFile, getPatientFilesBySlug, getSession, updatePatientCategoryNote, updatePatientFile, uploadPatientFile } from "./api.js";

const DEFAULT_PATIENT_PHOTO = "assets/default-patient.jpg";

const params = new URLSearchParams(window.location.search);
const slug = params.get("slug");

const filesBackLink = document.getElementById("filesBackLink");
const filesHeaderPhoto = document.getElementById("filesHeaderPhoto");
const filesPatientName = document.getElementById("filesPatientName");
const patientFilesContent = document.getElementById("patientFilesContent");
const patientFileInput = document.getElementById("patientFileInput");
const imagePreviewModal = document.getElementById("imagePreviewModal");
const imagePreviewImage = document.getElementById("imagePreviewImage");
const imagePreviewClose = document.getElementById("imagePreviewClose");
const FILE_CATEGORIES = [
  "Kimlik Resimleri",
  "Kuruma Giriş Bilgileri",
  "Vücut Muayenesi",
  "Kan Sonuçları",
  "Epikriz",
  "Tutanaklar",
  "Kıyafet ve Protezler"
];

let activePatient = null;
let patientFiles = [];
let currentUser = null;
let currentUploadCategory = FILE_CATEGORIES[0];

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 formatFileSize(bytes) {
  const size = Number(bytes || 0);
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

function syncHeader() {
  filesPatientName.textContent = activePatient?.fullName || "Hasta";
  filesBackLink.href = `detail.php?slug=${encodeURIComponent(slug || "")}`;

  filesHeaderPhoto.outerHTML = `<img id="filesHeaderPhoto" class="detail-header-avatar" src="${activePatient?.photoUrl || DEFAULT_PATIENT_PHOTO}" alt="${escapeHtml(activePatient?.fullName || "Yaşlı")} fotoğrafı" />`;
}

function isPreviewableImage(file) {
  return String(file?.mimeType || "").startsWith("image/");
}

function openImagePreview(src, name) {
  imagePreviewImage.src = src;
  imagePreviewImage.alt = name || "Dosya önizlemesi";
  imagePreviewModal.classList.remove("hidden");
  imagePreviewModal.setAttribute("aria-hidden", "false");
}

function closeImagePreview() {
  imagePreviewModal.classList.add("hidden");
  imagePreviewModal.setAttribute("aria-hidden", "true");
  imagePreviewImage.src = "";
}

function openUploadPicker(category) {
  currentUploadCategory = category;
  patientFileInput.click();
}

function bindFileActions() {
  patientFilesContent.querySelectorAll("[data-preview-file]").forEach((link) => {
    link.addEventListener("click", (event) => {
      const fileId = link.dataset.previewFile;
      const selectedFile = patientFiles.find((file) => String(file.id) === String(fileId));
      if (!selectedFile || !isPreviewableImage(selectedFile)) return;

      event.preventDefault();
      openImagePreview(selectedFile.url, selectedFile.name);
    });
  });

  patientFilesContent.querySelectorAll("[data-edit-file]").forEach((button) => {
    button.addEventListener("click", async () => {
      const fileId = button.dataset.editFile;
      const selectedFile = patientFiles.find((file) => String(file.id) === String(fileId));
      if (!selectedFile) return;

      const nextName = window.prompt("Dosya ismi", selectedFile.name || selectedFile.originalName || "");
      if (nextName === null) return;

      const trimmedName = nextName.trim();
      if (!trimmedName) {
        window.alert("Dosya ismi boş olamaz.");
        return;
      }

      try {
        const response = await updatePatientFile(Number(fileId), trimmedName);
        patientFiles = patientFiles.map((file) => (String(file.id) === String(fileId) ? response.file : file));
        renderFiles();
      } catch (error) {
        window.alert(error.message);
      }
    });
  });

  patientFilesContent.querySelectorAll("[data-delete-file]").forEach((button) => {
    button.addEventListener("click", async () => {
      const fileId = button.dataset.deleteFile;
      const selectedFile = patientFiles.find((file) => String(file.id) === String(fileId));
      if (!selectedFile) return;

      const confirmed = window.confirm(`${selectedFile.name} dosyasını silmek istiyor musunuz?`);
      if (!confirmed) return;

      try {
        await deletePatientFile(Number(fileId));
        patientFiles = patientFiles.filter((file) => String(file.id) !== String(fileId));
        renderFiles();
      } catch (error) {
        window.alert(error.message);
      }
    });
  });

  patientFilesContent.querySelectorAll("[data-add-category]").forEach((button) => {
    button.addEventListener("click", () => {
      openUploadPicker(button.dataset.addCategory || FILE_CATEGORIES[0]);
    });
  });

  patientFilesContent.querySelectorAll("[data-edit-category-note]").forEach((button) => {
    button.addEventListener("click", async () => {
      const category = button.dataset.editCategoryNote || "";
      if (!activePatient) return;

      const currentNote = activePatient?.clothingProstheticsNotes || "";
      const nextNote = window.prompt("Not", currentNote);
      if (nextNote === null) return;

      try {
        const response = await updatePatientCategoryNote(activePatient.id, category, nextNote);
        activePatient = response.patient;
        renderFiles();
      } catch (error) {
        window.alert(error.message);
      }
    });
  });
}

function renderFiles() {
  const groupedFiles = patientFiles.reduce((accumulator, file) => {
    const category = file.category || "Kimlik Resimleri";
    accumulator[category] ??= [];
    accumulator[category].push(file);
    return accumulator;
  }, {});

  const categories = FILE_CATEGORIES.map((category) => [category, groupedFiles[category] || []]);

  patientFilesContent.innerHTML = `
    <section class="detail-grid">
      ${categories
        .map(
          ([category, files]) => `
            <article class="panel-card detail-card patient-files-card">
              <div class="patient-files-card-header">
                <div>
                  <p class="eyebrow">Kategori</p>
                  <h2>${escapeHtml(category)}</h2>
                </div>
                <button class="file-category-add-btn" type="button" data-add-category="${escapeHtml(category)}" aria-label="${escapeHtml(category)} kategorisine dosya ekle">+</button>
              </div>
              ${
                category === "Kıyafet ve Protezler"
                  ? `
                    <div class="category-note-box">
                      <div class="category-note-header">
                        <span class="category-note-label">Not</span>
                        <button class="file-action-btn" type="button" data-edit-category-note="${escapeHtml(category)}" aria-label="Notu düzenle">✎</button>
                      </div>
                      <div class="category-note-display">${escapeHtml(activePatient?.clothingProstheticsNotes || "-")}</div>
                    </div>
                  `
                  : ""
              }
              <div class="patient-files-list">
                ${
                  files.length
                    ? files
                        .map(
                          (file) => `
                            <div class="patient-file-item">
                              <a class="patient-file-link" href="${file.url}" target="_blank" rel="noreferrer" data-preview-file="${file.id}">
                                <div class="patient-file-main">
                                  ${
                                    isPreviewableImage(file)
                                      ? `<img class="patient-file-thumb" src="${file.url}" alt="${escapeHtml(file.name)}" />`
                                      : `<div class="patient-file-thumb patient-file-thumb-fallback" aria-hidden="true">DOC</div>`
                                  }
                                  <div class="patient-file-copy">
                                  <strong>${escapeHtml(file.name)}</strong>
                                  <p>${formatDate(file.createdAt)} • ${formatFileSize(file.fileSize)}</p>
                                  </div>
                                </div>
                                <span class="patient-file-open" aria-hidden="true">${isPreviewableImage(file) ? "👁" : "↗"}</span>
                              </a>
                              <div class="patient-file-actions">
                                <button class="file-action-btn" type="button" data-edit-file="${file.id}" aria-label="Dosya ismini düzenle">✎</button>
                                ${
                                  currentUser?.role === "admin"
                                    ? `<button class="file-action-btn file-action-btn-danger" type="button" data-delete-file="${file.id}" aria-label="Dosyayı sil">×</button>`
                                    : ""
                                }
                              </div>
                            </div>
                          `
                        )
                        .join("")
                    : '<p class="empty-state">Bu kategoriye henüz dosya eklenmedi.</p>'
                }
              </div>
            </article>
          `
        )
        .join("")}
    </section>
  `;

  bindFileActions();
}

async function loadPage() {
  const data = await getPatientFilesBySlug(slug);
  activePatient = data.patient;
  patientFiles = data.files || [];
  syncHeader();
  renderFiles();
}

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

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

  try {
    await loadPage();
  } catch (error) {
    patientFilesContent.innerHTML = `<section class="panel-card"><p class="empty-state">${escapeHtml(error.message)}</p></section>`;
    return;
  }

  imagePreviewClose.addEventListener("click", closeImagePreview);
  imagePreviewModal.querySelector(".preview-modal-backdrop").addEventListener("click", closeImagePreview);
  imagePreviewModal.addEventListener("click", (event) => {
    if (event.target === imagePreviewModal) {
      closeImagePreview();
    }
  });
  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape" && !imagePreviewModal.classList.contains("hidden")) {
      closeImagePreview();
    }
  });

  patientFileInput.addEventListener("change", async () => {
    const file = patientFileInput.files?.[0];
    if (!file || !activePatient) return;

    const displayName = window.prompt("Dosyaya hangi isim verilsin?", "");
    if (displayName === null) {
      patientFileInput.value = "";
      return;
    }

    const trimmedName = displayName.trim();
    if (!trimmedName) {
      window.alert("Dosya ismi boş olamaz.");
      patientFileInput.value = "";
      return;
    }

    const formData = new FormData();
    formData.set("patientId", String(activePatient.id));
    formData.set("category", currentUploadCategory);
    formData.set("displayName", trimmedName);
    formData.set("file", file);

    try {
      const response = await uploadPatientFile(formData);
      patientFiles = response.files || [];
      renderFiles();
    } catch (error) {
      window.alert(error.message);
    } finally {
      patientFileInput.value = "";
    }
  });
}

init();
