'use strict';

appReady.then(async () => {
  const loading = document.getElementById('filesLoading');
  const empty = document.getElementById('filesEmpty');
  const wrap = document.getElementById('filesTableWrap');
  const body = document.getElementById('filesBody');
  const pagination = document.getElementById('pagination');
  const pageInfo = document.getElementById('pageInfo');
  const prev = document.getElementById('prevPage');
  const next = document.getElementById('nextPage');
  let page = 1;
  let pages = 1;

  function filenamePart(value) {
    return String(value || 'عهدة_الخضار')
      .trim()
      .replace(/[\\/:*?"<>|]+/g, '_')
      .replace(/\s+/g, '_')
      .slice(0, 80) || 'عهدة_الخضار';
  }

  async function load() {
    loading.hidden = false;
    empty.hidden = true;
    wrap.hidden = true;
    pagination.hidden = true;

    try {
      const result = await VegApi.request(`/api/custodies?page=${page}&limit=30`);
      pages = result.pages;
      loading.hidden = true;

      if (!result.rows.length) {
        empty.hidden = false;
        return;
      }

      body.innerHTML = result.rows.map((row) => {
        const custodyName = row.custody_name || `عهدة ${VegApi.formatDate(row.custody_date)}`;
        const editInfo = row.last_edited_by_name && row.last_edited_at
          ? `<div class="file-edited-note">آخر تعديل: ${VegApi.escapeHtml(row.last_edited_by_name)} · ${VegApi.formatDateTime(row.last_edited_at)}</div>`
          : '';

        return `
          <article class="file-card">
            <div class="file-card-top">
              <div class="file-title-wrap">
                <div class="file-date">${VegApi.escapeHtml(custodyName)}</div>
                <div class="file-code">${VegApi.formatDate(row.custody_date)} · ${VegApi.escapeHtml(row.custody_number)}</div>
              </div>
              <div class="file-cost"><strong class="money">${VegApi.formatNumber(row.total_cost, 2)}</strong><span>إجمالي التكلفة · ريال</span></div>
            </div>
            <div class="file-meta">
              <div class="file-meta-item"><div class="file-meta-label">المسجل</div><div class="file-meta-value">${VegApi.escapeHtml(row.created_by_name)}</div></div>
              <div class="file-meta-item"><div class="file-meta-label">الفئة</div><div class="file-meta-value">${VegApi.escapeHtml(row.created_by_category)}</div></div>
              <div class="file-meta-item"><div class="file-meta-label">عدد الأصناف</div><div class="file-meta-value money">${row.line_count}</div></div>
            </div>
            ${editInfo}
            <div class="file-actions file-actions-three">
              <a class="btn" href="/app/custody-view.html?id=${row.id}">فتح التفاصيل</a>
              <a class="btn btn-primary" href="/app/custody.html?edit=${row.id}&from=files">تعديل العهدة</a>
              <button
                class="btn btn-success"
                data-download-id="${row.id}"
                data-date="${VegApi.escapeHtml(String(row.custody_date).slice(0, 10))}"
                data-name="${VegApi.escapeHtml(custodyName)}"
                type="button"
              >تنزيل Excel</button>
            </div>
          </article>`;
      }).join('');

      wrap.hidden = false;
      pagination.hidden = result.total <= result.limit;
      pageInfo.textContent = `صفحة ${page} من ${pages}`;
      prev.disabled = page <= 1;
      next.disabled = page >= pages;
    } catch (error) {
      loading.textContent = error.message;
    }
  }

  body.addEventListener('click', async (event) => {
    const button = event.target.closest('[data-download-id]');
    if (!button) return;

    VegApi.setButtonLoading(button, true, 'جاري التنزيل...');
    try {
      await VegApi.download(
        `/api/custodies/${button.dataset.downloadId}/export`,
        `${filenamePart(button.dataset.name)}_${button.dataset.date}.xlsx`,
      );
    } catch (error) {
      VegApi.toast(error.message, 'error');
    } finally {
      VegApi.setButtonLoading(button, false);
    }
  });

  prev.addEventListener('click', () => {
    if (page > 1) {
      page -= 1;
      load();
    }
  });

  next.addEventListener('click', () => {
    if (page < pages) {
      page += 1;
      load();
    }
  });

  await load();
});
