import { checkMessage, deleteMessage, getMessages, getSession, getUnreadMessageCount, postMessage } from "./api.js";

let widgetInitialized = false;
let currentUser = null;

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",
    hour: "2-digit",
    minute: "2-digit"
  }).format(date).replace(",", " ");
}

function ensureWidgetMarkup() {
  if (document.getElementById("globalMessageWidget")) return;

  document.body.insertAdjacentHTML("beforeend", `
    <button id="globalMessageFab" class="global-message-fab" type="button" aria-label="Mesajları aç">
      <span aria-hidden="true">💬</span>
      <span id="globalMessageFabBadge" class="global-message-fab-badge hidden">0</span>
    </button>
    <div id="globalMessageWidget" class="global-message-widget hidden" aria-hidden="true">
      <div class="global-message-backdrop"></div>
      <section class="global-message-panel">
        <div class="global-message-header">
          <div>
            <p class="eyebrow">Mesajlar</p>
            <h3>Sohbet</h3>
          </div>
          <div class="global-message-header-actions">
            <button id="globalMessageCloseBtn" class="preview-close-btn" type="button" aria-label="Mesajları kapat">×</button>
          </div>
        </div>
        <div id="globalMessageList" class="global-message-list"></div>
        <form id="globalMessageForm" class="global-message-compose">
          <textarea id="globalMessageInput" rows="2" placeholder="Mesaj yaz"></textarea>
          <button class="btn btn-primary" type="submit">Gönder</button>
        </form>
        <p id="globalMessageStatus" class="helper-text hidden"></p>
      </section>
    </div>
  `);
}

function showStatus(message, isError = false) {
  const status = document.getElementById("globalMessageStatus");
  if (!status) return;
  status.textContent = message;
  status.classList.remove("hidden", "error-text");
  status.classList.add(isError ? "error-text" : "helper-text");
}

function syncFabBadge(count) {
  const badge = document.getElementById("globalMessageFabBadge");
  if (!badge) return;

  const unreadCount = Number(count || 0);
  badge.textContent = String(unreadCount);
  badge.classList.toggle("hidden", unreadCount <= 0);
}

async function renderMessages() {
  const list = document.getElementById("globalMessageList");
  if (!list) return;

  const messages = await getMessages();
  list.innerHTML = "";

  if (!messages.length) {
    list.innerHTML = '<p class="empty-state">Henüz mesaj yok.</p>';
    return;
  }

  [...messages].reverse().forEach((message) => {
    const isOwn = Number(message.userId || 0) === Number(currentUser?.id || 0);
    const canCheck = currentUser?.role !== "admin" && isOwn && !message.isChecked;
    const canDelete = currentUser?.role === "admin";
    const item = document.createElement("article");
    item.className = `global-message-item${isOwn ? " own" : ""}`;
    item.innerHTML = `
      <div class="global-message-bubble">
        <div class="global-message-meta">
          <strong>${escapeHtml(message.username)}</strong>
          <span>${escapeHtml(formatDateTime(message.createdAt))}</span>
        </div>
        <p>${escapeHtml(message.message)}</p>
        <div class="global-message-actions">
          ${message.isChecked && isOwn ? '<span class="global-message-checked-badge">✓ Check</span>' : ""}
          ${canCheck ? `<button class="file-action-btn global-message-check-btn" type="button" data-check-id="${message.id}" aria-label="Mesajı checkle">✓</button>` : ""}
          ${canDelete ? `<button class="file-action-btn file-action-btn-danger" type="button" data-delete-id="${message.id}" aria-label="Mesajı sil">×</button>` : ""}
        </div>
      </div>
    `;
    list.appendChild(item);
  });

  list.scrollTop = list.scrollHeight;

  list.querySelectorAll("[data-check-id]").forEach((button) => {
    button.addEventListener("click", async () => {
      try {
        await checkMessage(Number(button.dataset.checkId || 0));
        await renderMessages();
      } catch (error) {
        showStatus(error.message, true);
      }
    });
  });

  list.querySelectorAll("[data-delete-id]").forEach((button) => {
    button.addEventListener("click", async () => {
      if (!window.confirm("Bu mesajı silmek istiyor musunuz?")) return;
      try {
        await deleteMessage(Number(button.dataset.deleteId || 0));
        await renderMessages();
      } catch (error) {
        showStatus(error.message, true);
      }
    });
  });

  try {
    const unreadCount = await getUnreadMessageCount();
    syncFabBadge(unreadCount);
  } catch {
    syncFabBadge(0);
  }
}

function openWidget() {
  const widget = document.getElementById("globalMessageWidget");
  if (!widget) return;
  widget.classList.remove("hidden");
  widget.setAttribute("aria-hidden", "false");
  renderMessages().catch(() => {});
}

function closeWidget() {
  const widget = document.getElementById("globalMessageWidget");
  if (!widget) return;
  widget.classList.add("hidden");
  widget.setAttribute("aria-hidden", "true");
}

export async function initMessageWidget() {
  if (widgetInitialized) return;

  try {
    const session = await getSession();
    if (!session.authenticated) return;
    currentUser = session.user;
  } catch {
    return;
  }

  ensureWidgetMarkup();
  widgetInitialized = true;

  document.getElementById("globalMessageFab")?.addEventListener("click", openWidget);
  document.getElementById("globalMessageCloseBtn")?.addEventListener("click", closeWidget);
  document.querySelector("#globalMessageWidget .global-message-backdrop")?.addEventListener("click", closeWidget);

  document.getElementById("globalMessageForm")?.addEventListener("submit", async (event) => {
    event.preventDefault();
    const input = document.getElementById("globalMessageInput");
    const message = input?.value?.trim() || "";
    if (!message) {
      showStatus("Mesaj boş olamaz.", true);
      return;
    }

    try {
      await postMessage(message);
      input.value = "";
      showStatus("Mesaj gönderildi.");
      await renderMessages();
    } catch (error) {
      showStatus(error.message, true);
    }
  });

  window.setInterval(() => {
    const widget = document.getElementById("globalMessageWidget");
    if (widget && !widget.classList.contains("hidden")) {
      renderMessages().catch(() => {});
    }
  }, 15000);

  window.setInterval(() => {
    getUnreadMessageCount()
      .then((count) => {
        syncFabBadge(count);
      })
      .catch(() => {
        syncFabBadge(0);
      });
  }, 15000);

  try {
    const unreadCount = await getUnreadMessageCount();
    syncFabBadge(unreadCount);
  } catch {
    syncFabBadge(0);
  }
}
