'use strict';

appReady.then(async (user) => {
  const id = Number.parseInt(new URLSearchParams(location.search).get('id') || '', 10);
  const loading = document.getElementById('viewLoading');
  const content = document.getElementById('viewContent');
  const title = document.getElementById('viewTitle');
  const meta = document.getElementById('viewMeta');
  const total = document.getElementById('viewTotal');
  const lines = document.getElementById('viewLines');
  const body = document.getElementById('viewBody');
  const downloadButton = document.getElementById('downloadButton');
  const editButton = document.getElementById('editButton');
  const backButton = document.getElementById('backButton');
  const mobileBackLink = document.getElementById('mobileBackLink');

  document.getElementById('printButton').addEventListener('click', () => window.print());

  if (!Number.isInteger(id) || id <= 0) {
    loading.textContent = 'رقم العهدة غير صحيح.';
    return;
  }

  const backUrl = user.permissions.includes('files') ? '/app/files.html' : '/app/custody.html';
  backButton.href = backUrl;
  mobileBackLink.href = backUrl;
  editButton.href = `/app/custody.html?edit=${id}${user.permissions.includes('files') ? '&from=files' : ''}`;

  try {
    const result = await VegApi.request(`/api/custodies/${id}`);
    const custody = result.custody;
    const custodyName = custody.custody_name || `عهدة ${VegApi.formatDate(custody.custody_date)}`;

    title.textContent = custodyName;

    const metaParts = [
      `تاريخ العهدة: ${VegApi.formatDate(custody.custody_date)}`,
      `سجلها ${custody.created_by_name}`,
      custody.created_by_category,
    ];
    if (custody.last_edited_by_name && custody.last_edited_at) {
      metaParts.push(`آخر تعديل بواسطة ${custody.last_edited_by_name} في ${VegApi.formatDateTime(custody.last_edited_at)}`);
    }
    meta.textContent = metaParts.join(' · ');

    total.textContent = `${VegApi.formatNumber(custody.total_cost, 2)} ريال`;
    lines.textContent = custody.line_count;

    body.innerHTML = result.items.map((item) => `
      <tr>
        <td class="cell-hidden-mobile" data-label="رقم">${item.line_no}</td>
        <td class="cell-title text-right" data-label="اسم الصنف">${VegApi.escapeHtml(item.product_name)}</td>
        <td data-label="الوحدة">${VegApi.escapeHtml(item.unit_name || '—')}</td>
        <td class="money" data-label="الكمية">${VegApi.formatFlexible(item.quantity) || '—'}</td>
        <td class="money" data-label="الشد">${VegApi.formatFlexible(item.pack_size) || '—'}</td>
        <td class="money" data-label="العدد">${VegApi.formatFlexible(item.total_units) || '—'}</td>
        <td class="money" data-label="التكلفة">${VegApi.formatFlexible(item.unit_cost) || '—'}</td>
        <td class="money" data-label="إجمالي التكلفة">${VegApi.formatNumber(item.total_cost, 2) || '—'}</td>
        <td class="money" data-label="سعر الكيلو">${VegApi.formatNumber(item.cost_per_unit, 4) || '—'}</td>
        <td class="money" data-label="سعر البيع">${VegApi.formatNumber(item.sale_price, 2) || '—'}</td>
        <td class="text-right" data-label="الملاحظة">${VegApi.escapeHtml(item.note || '—')}</td>
      </tr>`).join('');

    loading.hidden = true;
    content.hidden = false;

    if (user.permissions.includes('files')) {
      downloadButton.hidden = false;
      downloadButton.addEventListener('click', async () => {
        VegApi.setButtonLoading(downloadButton, true, 'جاري التنزيل...');
        try {
          const safeName = custodyName.replace(/[\\/:*?"<>|]+/g, '_').replace(/\s+/g, '_').slice(0, 80);
          await VegApi.download(
            `/api/custodies/${id}/export`,
            `${safeName}_${String(custody.custody_date).slice(0, 10)}.xlsx`,
          );
        } catch (error) {
          VegApi.toast(error.message, 'error');
        } finally {
          VegApi.setButtonLoading(downloadButton, false);
        }
      });
    }
  } catch (error) {
    loading.textContent = error.message;
  }
});
