let storageProducts = [];
let storageFiltered = [];
let storageTags = [];
let storageEditingId = null;

export async function initStoragePage() {
  bindStorageEvents();
  await loadProducts();
}

function bindStorageEvents() {
  const addBtn = document.getElementById("storage-add-btn");
  const closeBtn = document.getElementById("storage-drawer-close");
  const cancelBtn = document.getElementById("storage-cancel-btn");
  const backdrop = document.getElementById("storage-drawer-backdrop");
  const form = document.getElementById("storage-form");
  const searchInput = document.getElementById("storage-search");
  const sortSelect = document.getElementById("storage-sort");
  const tagInput = document.getElementById("storage-tag-input");

  if (addBtn) addBtn.addEventListener("click", openNewProductDrawer);
  if (closeBtn) closeBtn.addEventListener("click", closeDrawer);
  if (cancelBtn) cancelBtn.addEventListener("click", closeDrawer);
  if (backdrop) backdrop.addEventListener("click", closeDrawer);
  if (form) form.addEventListener("submit", handleSaveProduct);
  if (searchInput) searchInput.addEventListener("input", applyFilters);
  if (sortSelect) sortSelect.addEventListener("change", applyFilters);

  if (tagInput) {
    tagInput.addEventListener("keydown", handleTagKeydown);
    tagInput.addEventListener("blur", flushTagInput);
  }
}

async function loadProducts() {
  try {
    const response = await fetch("/api/urunler");
    const data = await response.json();

    storageProducts = Array.isArray(data) ? data.map(normalizeProduct) : [];
    applyFilters();
  } catch (_) {
    renderStorageList([]);
    window.showToast("Ürünler yüklenemedi", "err");
  }
}

function normalizeProduct(item) {
  const tagList = parseTags(item.etiketler);
  return {
    id: item.id,
    ad: item.ad || "",
    stok: Number(item.stok || 0),
    fiyat: Number(item.fiyat || 0),
    maliyet: item.maliyet === null || item.maliyet === undefined || item.maliyet === "" ? "" : Number(item.maliyet),
    aciklama: item.aciklama || "",
    etiketler: tagList,
    olusturma_tarihi: item.olusturma_tarihi || ""
  };
}

function applyFilters() {
  const searchValue = (document.getElementById("storage-search")?.value || "").trim().toLocaleLowerCase("tr-TR");
  const sortValue = document.getElementById("storage-sort")?.value || "alpha";

  storageFiltered = storageProducts.filter((product) => {
    if (!searchValue) return true;

    const haystack = [
      product.ad,
      product.aciklama,
      ...(product.etiketler || [])
    ]
      .join(" ")
      .toLocaleLowerCase("tr-TR");

    return haystack.includes(searchValue);
  });

  storageFiltered.sort((a, b) => {
    if (sortValue === "newest") return Number(b.id) - Number(a.id);
    if (sortValue === "stock_desc") return Number(b.stok) - Number(a.stok);
    if (sortValue === "stock_asc") return Number(a.stok) - Number(b.stok);
    return a.ad.localeCompare(b.ad, "tr");
  });

  renderStorageList(storageFiltered);
}

function renderStorageList(list) {
  const root = document.getElementById("storage-list");
  if (!root) return;

  if (!Array.isArray(list) || list.length === 0) {
    root.innerHTML = `<div class="storage-empty">Gösterilecek ürün bulunamadı.</div>`;
    return;
  }

  root.innerHTML = list
    .map((product) => {
      const tagsHtml = (product.etiketler || []).length
        ? `<div class="storage-tags">
            ${product.etiketler.map((tag) => `<span class="storage-tag">${escapeHtml(tag)}</span>`).join("")}
           </div>`
        : "";

      const description = product.aciklama
        ? `<div class="storage-desc">${escapeHtml(product.aciklama)}</div>`
        : "";

      return `
        <div class="storage-item">
          <div class="storage-name-cell">
            <div class="storage-name">${escapeHtml(product.ad)}</div>
            ${description}
            ${tagsHtml}
          </div>

          <div class="storage-stock">${Number(product.stok)}</div>
          <div class="storage-price">₺${formatMoney(product.fiyat)}</div>

          <div class="storage-actions">
            <button type="button" class="storage-edit-btn" data-id="${product.id}">Düzenle</button>
            <button type="button" class="storage-delete-btn" data-id="${product.id}">Sil</button>
          </div>
        </div>
      `;
    })
    .join("");

  root.querySelectorAll(".storage-edit-btn").forEach((button) => {
    button.addEventListener("click", () => openEditDrawer(Number(button.dataset.id)));
  });

  root.querySelectorAll(".storage-delete-btn").forEach((button) => {
    button.addEventListener("click", () => handleDeleteProduct(Number(button.dataset.id)));
  });
}

function openNewProductDrawer() {
  storageEditingId = null;
  storageTags = [];

  document.getElementById("storage-drawer-title").textContent = "Yeni Ürün";
  document.getElementById("storage-drawer-sub").textContent = "Ürün bilgilerini doldurun.";
  document.getElementById("storage-product-id").value = "";
  document.getElementById("storage-name").value = "";
  document.getElementById("storage-stock").value = "0";
  document.getElementById("storage-price").value = "";
  document.getElementById("storage-description").value = "";
  document.getElementById("storage-cost").value = "";
  document.getElementById("storage-tag-input").value = "";
  renderTagChips();

  showDrawer();
}

function openEditDrawer(id) {
  const product = storageProducts.find((item) => item.id === id);
  if (!product) return;

  storageEditingId = id;
  storageTags = [...(product.etiketler || [])];

  document.getElementById("storage-drawer-title").textContent = "Ürünü Düzenle";
  document.getElementById("storage-drawer-sub").textContent = "Ürün bilgilerini güncelleyin.";
  document.getElementById("storage-product-id").value = String(product.id);
  document.getElementById("storage-name").value = product.ad || "";
  document.getElementById("storage-stock").value = String(product.stok ?? 0);
  document.getElementById("storage-price").value = product.fiyat ?? "";
  document.getElementById("storage-description").value = product.aciklama || "";
  document.getElementById("storage-cost").value = product.maliyet === "" ? "" : product.maliyet;
  document.getElementById("storage-tag-input").value = "";
  renderTagChips();

  showDrawer();
}

function showDrawer() {
  document.getElementById("storage-drawer").classList.add("show");
  document.getElementById("storage-drawer-backdrop").classList.add("show");
}

function closeDrawer() {
  document.getElementById("storage-drawer").classList.remove("show");
  document.getElementById("storage-drawer-backdrop").classList.remove("show");
}

async function handleSaveProduct(event) {
  event.preventDefault();
  flushTagInput();

  const payload = buildProductPayload();
  if (!payload) return;

  try {
    let response;

    if (storageEditingId) {
      response = await fetch(`/api/urunler/${storageEditingId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
    } else {
      response = await fetch("/api/urunler", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
    }

    const data = await response.json();

    if (!response.ok || !data.ok) {
      window.showToast(data.hata || "İşlem tamamlanamadı", "err");
      return;
    }

    window.showToast(storageEditingId ? "Ürün güncellendi" : "Ürün eklendi", "ok");
    closeDrawer();
    await loadProducts();
  } catch (_) {
    window.showToast("Ürün kaydedilemedi", "err");
  }
}

function buildProductPayload() {
  const ad = document.getElementById("storage-name").value.trim();
  const stok = Number(document.getElementById("storage-stock").value);
  const fiyat = Number(document.getElementById("storage-price").value);
  const aciklama = document.getElementById("storage-description").value.trim();
  const maliyetRaw = document.getElementById("storage-cost").value.trim();

  if (!ad) {
    window.showToast("Ürün adı zorunlu", "err");
    return null;
  }

  if (!Number.isFinite(stok) || stok < 0) {
    window.showToast("Stok 0 veya daha büyük olmalı", "err");
    return null;
  }

  if (!Number.isFinite(fiyat) || fiyat < 0) {
    window.showToast("Fiyat 0 veya daha büyük olmalı", "err");
    return null;
  }

  if (maliyetRaw !== "" && (!Number.isFinite(Number(maliyetRaw)) || Number(maliyetRaw) < 0)) {
    window.showToast("Maliyet hatalı", "err");
    return null;
  }

  return {
    ad,
    stok,
    fiyat,
    aciklama,
    maliyet: maliyetRaw === "" ? null : Number(maliyetRaw),
    etiketler: storageTags.join(", ")
  };
}

async function handleDeleteProduct(id) {
  const product = storageProducts.find((item) => item.id === id);
  if (!product) return;

  const confirmed = window.confirm(`"${product.ad}" ürününü silmek istiyor musunuz?`);
  if (!confirmed) return;

  try {
    const response = await fetch(`/api/urunler/${id}`, {
      method: "DELETE"
    });

    const data = await response.json();
    if (!response.ok || !data.ok) {
      window.showToast(data.hata || "Ürün silinemedi", "err");
      return;
    }

    window.showToast("Ürün silindi", "ok");
    await loadProducts();
  } catch (_) {
    window.showToast("Ürün silinemedi", "err");
  }
}

function handleTagKeydown(event) {
  if (event.key === "," || event.key === "Enter") {
    event.preventDefault();
    pushTag(event.target.value);
    event.target.value = "";
    return;
  }

  if (event.key === "Backspace" && !event.target.value.trim() && storageTags.length > 0) {
    storageTags.pop();
    renderTagChips();
  }
}

function flushTagInput() {
  const input = document.getElementById("storage-tag-input");
  if (!input) return;

  if (input.value.trim()) {
    pushTag(input.value);
    input.value = "";
  }
}

function pushTag(rawValue) {
  const parts = String(rawValue || "")
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);

  parts.forEach((part) => {
    const normalized = normalizeTag(part);
    if (!normalized) return;

    const exists = storageTags.some(
      (tag) => tag.toLocaleLowerCase("tr-TR") === normalized.toLocaleLowerCase("tr-TR")
    );

    if (!exists) {
      storageTags.push(normalized);
    }
  });

  renderTagChips();
}

function normalizeTag(value) {
  const cleaned = String(value || "").trim().replace(/\s+/g, " ");
  if (!cleaned) return "";
  return cleaned.charAt(0).toLocaleUpperCase("tr-TR") + cleaned.slice(1);
}

function renderTagChips() {
  const root = document.getElementById("storage-tags-list");
  if (!root) return;

  root.innerHTML = storageTags
    .map(
      (tag, index) => `
        <span class="storage-tag-chip">
          <span>${escapeHtml(tag)}</span>
          <button type="button" class="storage-tag-remove" data-index="${index}">×</button>
        </span>
      `
    )
    .join("");

  root.querySelectorAll(".storage-tag-remove").forEach((button) => {
    button.addEventListener("click", () => {
      const index = Number(button.dataset.index);
      storageTags.splice(index, 1);
      renderTagChips();
    });
  });
}

function parseTags(value) {
  if (!value) return [];
  return String(value)
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);
}

function formatMoney(value) {
  return Number(value || 0).toLocaleString("tr-TR", {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  });
}

function escapeHtml(value) {
  return String(value || "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}