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

const logSearchInput = document.getElementById("logSearchInput");
const logFromInput = document.getElementById("logFromInput");
const logToInput = document.getElementById("logToInput");
const logTodayBtn = document.getElementById("logTodayBtn");
const logLast7Btn = document.getElementById("logLast7Btn");
const logLast30Btn = document.getElementById("logLast30Btn");
const logOnlineUsersWrap = document.getElementById("logOnlineUsersWrap");
const logOnlineUsers = document.getElementById("logOnlineUsers");
const logResultsInfo = document.getElementById("logResultsInfo");
const logList = document.getElementById("logList");
const logPagination = document.getElementById("logPagination");
const logPrevPageBtn = document.getElementById("logPrevPageBtn");
const logPageInfo = document.getElementById("logPageInfo");
const logNextPageBtn = document.getElementById("logNextPageBtn");
const welcomeMessage = document.getElementById("welcomeMessage");
const logoutBtn = document.getElementById("logoutBtn");
const mobilePageNavToggle = document.getElementById("mobilePageNavToggle");
const logsPageNav = document.getElementById("logsPageNav");

let debounceTimer = 0;
let mobileNavOpen = false;
let currentPage = 1;
let totalPages = 1;

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

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

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

function renderLogs(logs, total = logs.length) {
  logResultsInfo.textContent = `${total} kayıt`;
  logList.innerHTML = "";

  if (!logs.length) {
    logList.innerHTML = '<p class="empty-state">Aramaya uygun log kaydı bulunamadı.</p>';
    return;
  }

  logs.forEach((log) => {
    const item = document.createElement("article");
    item.className = "log-item";
    item.innerHTML = `
      <div class="log-item-top">
        <span class="status-badge">${escapeHtml(formatDateTime(log.createdAt))}</span>
        <span class="room-badge">${escapeHtml(log.actorUsername)}</span>
      </div>
      <h3>${escapeHtml(log.actionSummary)}</h3>
      <p class="patient-diagnosis">${escapeHtml(log.actionDetails || "-")}</p>
    `;
    logList.appendChild(item);
  });
}

function renderPagination(page, pages, total) {
  currentPage = page;
  totalPages = pages;

  const shouldShow = total > 30 && pages > 1;
  logPagination?.classList.toggle("hidden", !shouldShow);
  if (!shouldShow) return;

  logPageInfo.textContent = `Sayfa ${page} / ${pages}`;
  logPrevPageBtn.disabled = page <= 1;
  logNextPageBtn.disabled = page >= pages;
}

function renderOnlineUsers(users) {
  const hasDateFilter = logFromInput.value.trim() !== "" || logToInput.value.trim() !== "";
  if (!hasDateFilter) {
    logOnlineUsersWrap?.classList.add("hidden");
    if (logOnlineUsers) logOnlineUsers.innerHTML = "";
    return;
  }

  logOnlineUsersWrap?.classList.remove("hidden");

  if (!users.length) {
    logOnlineUsers.innerHTML = '<span class="log-online-user-chip">Kullanıcı yok</span>';
    return;
  }

  logOnlineUsers.innerHTML = users.map((user) => `
    <span class="log-online-user-chip">${escapeHtml(user.username)}</span>
  `).join("");
}

async function loadLogs() {
  try {
    const data = await getLogs({
      q: logSearchInput.value.trim(),
      from: logFromInput.value,
      to: logToInput.value,
      page: currentPage
    });
    renderLogs(data.logs || [], data.total || 0);
    renderOnlineUsers(data.onlineUsers || []);
    renderPagination(data.page || 1, data.totalPages || 1, data.total || 0);
  } catch (error) {
    logList.innerHTML = `<p class="error-text">${escapeHtml(error.message)}</p>`;
    logOnlineUsersWrap?.classList.add("hidden");
    logPagination?.classList.add("hidden");
  }
}

function queueLoad() {
  window.clearTimeout(debounceTimer);
  debounceTimer = window.setTimeout(() => {
    currentPage = 1;
    loadLogs();
  }, 220);
}

function toDateValue(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function applyQuickRange(type) {
  const now = new Date();
  const start = new Date(now);

  if (type === "today") {
    start.setHours(0, 0, 0, 0);
  } else if (type === "last7") {
    start.setDate(start.getDate() - 6);
    start.setHours(0, 0, 0, 0);
  } else if (type === "last30") {
    start.setDate(start.getDate() - 29);
    start.setHours(0, 0, 0, 0);
  }

  logFromInput.value = toDateValue(start);
  logToInput.value = toDateValue(now);
  currentPage = 1;
  return loadLogs();
}

function setMobileNavState(isOpen) {
  mobileNavOpen = Boolean(isOpen);
  if (!mobilePageNavToggle || !logsPageNav) return;

  logsPageNav.classList.toggle("page-nav-mobile-open", mobileNavOpen);
  mobilePageNavToggle.setAttribute("aria-expanded", mobileNavOpen ? "true" : "false");
}

function syncMobileHeader() {
  if (!mobilePageNavToggle || !logsPageNav) return;

  const isMobile = window.innerWidth <= 860;
  mobilePageNavToggle.classList.toggle("hidden", !isMobile);

  if (isMobile) {
    logsPageNav.classList.remove("hidden");
    logsPageNav.classList.toggle("page-nav-mobile-open", mobileNavOpen);
    return;
  }

  logsPageNav.classList.remove("page-nav-mobile-open");
  logsPageNav.classList.remove("hidden");
  mobilePageNavToggle.setAttribute("aria-expanded", "false");
  mobileNavOpen = false;
}

async function init() {
  const session = await getSession();
  const username = String(session.user?.username ?? "").toLocaleLowerCase("tr");
  if (!session.authenticated || username !== "emir") {
    window.location.replace("index.php");
    return;
  }

  welcomeMessage.textContent = `Hoş geldin ${session.user.username}`;

  logSearchInput.addEventListener("input", queueLoad);
  logFromInput.addEventListener("change", async () => {
    currentPage = 1;
    await loadLogs();
  });
  logToInput.addEventListener("change", async () => {
    currentPage = 1;
    await loadLogs();
  });
  logTodayBtn?.addEventListener("click", async () => {
    await applyQuickRange("today");
  });
  logLast7Btn?.addEventListener("click", async () => {
    await applyQuickRange("last7");
  });
  logLast30Btn?.addEventListener("click", async () => {
    await applyQuickRange("last30");
  });
  logPrevPageBtn?.addEventListener("click", async () => {
    if (currentPage <= 1) return;
    currentPage -= 1;
    await loadLogs();
  });
  logNextPageBtn?.addEventListener("click", async () => {
    if (currentPage >= totalPages) return;
    currentPage += 1;
    await loadLogs();
  });
  logoutBtn?.addEventListener("click", async () => {
    try {
      await logout();
    } finally {
      window.location.replace("index.php");
    }
  });
  mobilePageNavToggle?.addEventListener("click", () => {
    setMobileNavState(!mobileNavOpen);
  });
  window.addEventListener("resize", syncMobileHeader);
  syncMobileHeader();

  await loadLogs();
}

init();
