'use strict';

appReady.then(async (user) => {
  const query = new URLSearchParams(window.location.search);
  const requestedEditId = Number.parseInt(query.get('edit') || '', 10);
  const returnToFiles = query.get('from') === 'files';
  const canCreateCustody = user.permissions.includes('custody');

  const currentLoading = document.getElementById('currentLoading');
  const currentEmpty = document.getElementById('currentEmpty');
  const currentContent = document.getElementById('currentContent');
  const currentName = document.getElementById('currentName');
  const currentMeta = document.getElementById('currentMeta');
  const currentTotal = document.getElementById('currentTotal');
  const currentLines = document.getElementById('currentLines');
  const currentBody = document.getElementById('currentBody');
  const currentToggle = document.getElementById('currentToggle');
  const currentPanel = document.getElementById('currentPanel');
  const editCurrentButton = document.getElementById('editCurrentButton');

  const editorSection = document.getElementById('editorSection');
  const editorBody = document.getElementById('editorBody');
  const editorTitle = document.getElementById('editorTitle');
  const editorSubtitle = document.getElementById('editorSubtitle');
  const editorModeBadge = document.getElementById('editorModeBadge');
  const custodyNameInput = document.getElementById('custodyName');
  const custodyDateInput = document.getElementById('custodyDate');
  const lockedDateNotice = document.getElementById('lockedDateNotice');
  const draftTotal = document.getElementById('draftTotal');
  const draftLines = document.getElementById('draftLines');
  const autosaveStatus = document.getElementById('autosaveStatus');
  const draftNotice = document.getElementById('draftNotice');
  const newButton = document.getElementById('newCustodyButton');
  const saveButton = document.getElementById('saveCustodyButton');
  const saveButtonText = document.getElementById('saveButtonText');
  const savebarCopy = document.getElementById('savebarCopy');
  const addRowButton = document.getElementById('addRowButton');
  const discardButton = document.getElementById('discardDraftButton');
  const discardButtonText = document.getElementById('discardButtonText');

  const createStorageKey = `veg_custody_draft_${user.id}`;
  const unitOptions = ['كرتون', 'صندوق', 'علبة', 'حبة'];
  let draft = null;
  let saveTimer = null;

  newButton.hidden = !canCreateCustody;

  function todayIso() {
    const parts = new Intl.DateTimeFormat('en-CA', {
      timeZone: 'Asia/Riyadh',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    }).formatToParts(new Date());
    const map = Object.fromEntries(parts.map((part) => [part.type, part.value]));
    return `${map.year}-${map.month}-${map.day}`;
  }

  function requestId() {
    if (window.crypto?.randomUUID) return window.crypto.randomUUID();
    const bytes = new Uint8Array(24);
    window.crypto.getRandomValues(bytes);
    return [...bytes].map((value) => value.toString(16).padStart(2, '0')).join('');
  }

  function storageKeyFor(value = draft) {
    if (value?.mode === 'edit' && value.custodyId) {
      return `veg_custody_edit_${user.id}_${value.custodyId}`;
    }
    return createStorageKey;
  }

  function removeStoredDraft(value = draft) {
    if (value) localStorage.removeItem(storageKeyFor(value));
  }

  function numberValue(value) {
    if (value === '' || value === null || value === undefined) return null;
    const number = Number(value);
    return Number.isFinite(number) && number >= 0 ? number : null;
  }

  function calculate(item) {
    const quantity = numberValue(item.quantity);
    const packSize = numberValue(item.packSize);
    const unitCost = numberValue(item.unitCost);
    const totalUnits = quantity !== null && packSize !== null ? quantity * packSize : null;
    const totalCost = quantity !== null && unitCost !== null ? quantity * unitCost : null;
    const costPerUnit = totalUnits > 0 && totalCost !== null ? totalCost / totalUnits : null;
    return { totalUnits, totalCost, costPerUnit };
  }

  function display(value, decimals = 2) {
    return value === null || value === undefined || !Number.isFinite(value)
      ? '—'
      : VegApi.formatNumber(value, decimals);
  }

  function normalizeUnit(value) {
    const unit = String(value || '').trim();
    if (unit === 'حبه') return 'حبة';
    return unit;
  }

  function unitSelectHtml(value) {
    const selected = normalizeUnit(value);
    return `
      <select class="input unit-select" data-field="unitName" aria-label="الوحدة">
        <option value="">اختر الوحدة</option>
        ${unitOptions.map((unit) => `
          <option value="${unit}" ${selected === unit ? 'selected' : ''}>${unit}</option>
        `).join('')}
      </select>`;
  }

  function itemFromApi(item) {
    return {
      productId: item.product_id,
      productName: item.product_name,
      unitName: item.unit_name || '',
      quantity: item.quantity,
      packSize: item.pack_size,
      unitCost: item.unit_cost,
      salePrice: item.sale_price,
      note: item.note || '',
    };
  }

  function editReturnUrl() {
    if (returnToFiles && user.permissions.includes('files')) return '/app/files.html';
    return '/app/custody.html';
  }

  async function loadCurrent() {
    currentLoading.hidden = false;
    currentLoading.textContent = 'جاري تحميل آخر عهدة...';
    currentEmpty.hidden = true;
    currentContent.hidden = true;

    try {
      const result = await VegApi.request('/api/custodies/current');
      currentLoading.hidden = true;

      if (!result.custody) {
        currentEmpty.hidden = false;
        currentName.textContent = 'لا توجد عهدة محفوظة';
        currentMeta.textContent = 'ابدأ بإضافة أول عهدة';
        return;
      }

      const custody = result.custody;
      currentName.textContent = custody.custody_name || `عهدة ${VegApi.formatDate(custody.custody_date)}`;

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

      currentTotal.textContent = `${VegApi.formatNumber(custody.total_cost, 2)} ريال`;
      currentLines.textContent = custody.line_count;
      editCurrentButton.href = `/app/custody.html?edit=${custody.id}`;

      currentBody.innerHTML = result.items.map((item) => `
        <tr>
          <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('');

      currentContent.hidden = false;
    } catch (error) {
      currentLoading.hidden = false;
      currentLoading.textContent = error.message;
    }
  }

  function rowActionHtml(item) {
    if (draft?.mode === 'edit') {
      return `
        <button class="btn btn-danger btn-small" data-action="remove-row" type="button">
          إزالة من العهدة
        </button>`;
    }

    const productId = Number(item.productId) > 0 ? Number(item.productId) : null;
    if (productId) {
      return `
        <button class="btn btn-danger btn-small product-delete-button" data-action="delete-product" type="button">
          حذف الصنف
        </button>
        <span class="product-delete-note">لا يؤثر على العهد القديمة</span>`;
    }

    return `
      <button class="btn btn-danger btn-small" data-action="remove-row" type="button">
        إلغاء
      </button>`;
  }

  function rowHtml(item, index) {
    const calc = calculate(item);

    return `
      <tr data-index="${index}">
        <td class="row-number cell-row-number" data-label="رقم">${index + 1}</td>
        <td class="cell-product" data-label="اسم الصنف">
          <input class="input product-input" data-field="productName" maxlength="180" placeholder="اسم الصنف" value="${VegApi.escapeHtml(item.productName || '')}">
        </td>
        <td data-label="الوحدة">${unitSelectHtml(item.unitName)}</td>
        <td data-label="الكمية"><input class="input input-number" data-field="quantity" type="number" min="0" step="0.001" inputmode="decimal" value="${VegApi.escapeHtml(item.quantity ?? '')}"></td>
        <td data-label="الشد"><input class="input input-number" data-field="packSize" type="number" min="0" step="0.001" inputmode="decimal" value="${VegApi.escapeHtml(item.packSize ?? '')}"></td>
        <td class="computed-cell" data-label="العدد" aria-readonly="true"><span class="computed-number" data-computed="totalUnits">${display(calc.totalUnits, 3)}</span></td>
        <td data-label="التكلفة"><input class="input input-number" data-field="unitCost" type="number" min="0" step="0.001" inputmode="decimal" value="${VegApi.escapeHtml(item.unitCost ?? '')}"></td>
        <td class="computed-cell" data-label="إجمالي التكلفة" aria-readonly="true"><span class="computed-number" data-computed="totalCost">${display(calc.totalCost, 2)}</span></td>
        <td class="computed-cell" data-label="سعر الكيلو" aria-readonly="true"><span class="computed-number" data-computed="costPerUnit">${display(calc.costPerUnit, 4)}</span></td>
        <td data-label="سعر البيع"><input class="input input-number" data-field="salePrice" type="number" min="0" step="0.01" inputmode="decimal" value="${VegApi.escapeHtml(item.salePrice ?? '')}"></td>
        <td class="cell-note" data-label="ملاحظة"><input class="input note-input" data-field="note" maxlength="255" placeholder="اختياري" value="${VegApi.escapeHtml(item.note || '')}"></td>
        <td class="cell-remove" data-label="إجراء">${rowActionHtml(item)}</td>
      </tr>`;
  }

  function configureEditorMode() {
    const editing = draft.mode === 'edit';

    editorModeBadge.textContent = editing ? 'تعديل عهدة محفوظة' : 'عهدة جديدة';
    editorTitle.textContent = editing ? `تعديل: ${draft.custodyName}` : 'إضافة عهدة جديدة';
    editorSubtitle.textContent = editing
      ? 'يمكن تعديل الاسم والبيانات، بينما يبقى تاريخ العهدة الأصلي ثابتًا'
      : 'تُراجع جميع الحسابات مرة أخرى داخل السيرفر قبل الحفظ';

    custodyDateInput.disabled = editing;
    custodyDateInput.classList.toggle('input-locked', editing);
    lockedDateNotice.hidden = !editing;
    discardButtonText.textContent = editing ? 'إلغاء التعديل' : 'إلغاء المسودة';
    saveButtonText.textContent = editing ? 'حفظ التعديلات' : 'حفظ العهدة نهائيًا';
    savebarCopy.textContent = editing
      ? 'سيتم تحديث نفس العهدة دون إنشاء ملف جديد ودون تغيير تاريخها الأصلي.'
      : 'بعد الحفظ ستصبح هذه العهدة هي العهدة الحالية وتبقى السابقة داخل الملفات.';
  }

  function renderEditor() {
    editorBody.innerHTML = draft.items.map(rowHtml).join('');
    custodyNameInput.value = draft.custodyName || '';
    custodyDateInput.value = draft.custodyDate;
    custodyDateInput.max = todayIso();
    configureEditorMode();
    editorSection.hidden = false;
    updateDraftSummary();
  }

  function updateRow(row, item) {
    const calc = calculate(item);
    row.querySelector('[data-computed="totalUnits"]').textContent = display(calc.totalUnits, 3);
    row.querySelector('[data-computed="totalCost"]').textContent = display(calc.totalCost, 2);
    row.querySelector('[data-computed="costPerUnit"]').textContent = display(calc.costPerUnit, 4);
  }

  function updateDraftSummary() {
    const total = draft.items.reduce((sum, item) => sum + (calculate(item).totalCost || 0), 0);
    draftTotal.textContent = `${VegApi.formatNumber(total, 2)} ريال`;
    draftLines.textContent = draft.items.length;
  }

  function saveDraftSoon() {
    autosaveStatus.textContent = 'جاري الحفظ...';
    clearTimeout(saveTimer);
    saveTimer = setTimeout(() => {
      draft.updatedAt = new Date().toISOString();
      autosaveStatus.textContent = 'محفوظة على الجهاز';
    }, 350);
  }

  async function startNew() {
    if (!canCreateCustody) {
      VegApi.toast('ليس لديك صلاحية لإضافة عهدة جديدة.', 'error');
      return;
    }

    if (draft?.mode === 'create') {
      editorSection.hidden = false;
      editorSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
      return;
    }

    if (draft?.mode === 'edit' && !confirm('لديك تعديل مفتوح. هل تريد تركه وبدء عهدة جديدة؟')) return;
    if (draft) removeStoredDraft();

    VegApi.setButtonLoading(newButton, true, 'جاري التجهيز...');
    try {
      const template = await VegApi.request('/api/custodies/template');
      draft = {
        mode: 'create',
        custodyName: '',
        custodyDate: template.custodyDate,
        items: template.items,
        createdForUser: user.id,
        requestId: requestId(),
        updatedAt: new Date().toISOString(),
      };
      localStorage.setItem(storageKeyFor(), JSON.stringify(draft));
      draftNotice.hidden = true;
      renderEditor();
      editorSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
      setTimeout(() => custodyNameInput.focus(), 250);
    } catch (error) {
      VegApi.toast(error.message, 'error');
    } finally {
      VegApi.setButtonLoading(newButton, false);
    }
  }

  async function startEdit(custodyId) {
    if (!Number.isInteger(custodyId) || custodyId <= 0) {
      VegApi.toast('رقم العهدة غير صحيح.', 'error');
      return;
    }

    const key = `veg_custody_edit_${user.id}_${custodyId}`;
    const stored = localStorage.getItem(key);

    try {
      const result = await VegApi.request(`/api/custodies/${custodyId}`);
      const serverDraft = {
        mode: 'edit',
        custodyId,
        custodyName: result.custody.custody_name || `عهدة ${VegApi.formatDate(result.custody.custody_date)}`,
        custodyDate: String(result.custody.custody_date).slice(0, 10),
        items: result.items.map(itemFromApi),
        createdForUser: user.id,
        updatedAt: new Date().toISOString(),
      };

      if (stored) {
        try {
          const parsed = JSON.parse(stored);
          if (parsed?.mode === 'edit' && parsed.custodyId === custodyId && Array.isArray(parsed.items)) {
            draft = parsed;
            draftNotice.hidden = false;
          } else {
            draft = serverDraft;
            localStorage.removeItem(key);
          }
        } catch (_) {
          draft = serverDraft;
          localStorage.removeItem(key);
        }
      } else {
        draft = serverDraft;
      }

      renderEditor();
      editorSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } catch (error) {
      VegApi.toast(error.message, 'error');
    }
  }

  function updateDraftField(event) {
    const input = event.target.closest('[data-field]');
    if (!input || !draft) return;
    const row = input.closest('tr');
    const index = Number(row.dataset.index);
    const field = input.dataset.field;
    draft.items[index][field] = input.value;
    updateRow(row, draft.items[index]);
    updateDraftSummary();
    saveDraftSoon();
  }

  editorBody.addEventListener('input', updateDraftField);
  editorBody.addEventListener('change', updateDraftField);

  editorBody.addEventListener('click', async (event) => {
    const button = event.target.closest('[data-action]');
    if (!button || !draft) return;

    const row = button.closest('tr');
    const index = Number(row.dataset.index);
    const item = draft.items[index];

    if (button.dataset.action === 'remove-row') {
      const message = draft.mode === 'edit'
        ? `إزالة «${item.productName}» من هذه العهدة فقط؟`
        : 'هل تريد إزالة هذا السطر؟';
      if (!confirm(message)) return;
      draft.items.splice(index, 1);
      renderEditor();
      saveDraftSoon();
      return;
    }

    if (button.dataset.action !== 'delete-product') return;

    const accepted = confirm(
      `هل تريد حذف الصنف «${item.productName}» من قائمة الأصناف؟\n\n`
      + 'لن يظهر في العهد الجديدة، ولن تتأثر العهد المحفوظة سابقًا.',
    );
    if (!accepted) return;

    VegApi.setButtonLoading(button, true, 'جاري الحذف...');
    try {
      await VegApi.request(`/api/products/${item.productId}`, { method: 'DELETE' });
      draft.items.splice(index, 1);
      renderEditor();
      saveDraftSoon();
      VegApi.toast('تم حذف الصنف من العهد القادمة.');
    } catch (error) {
      VegApi.toast(error.message, 'error');
      VegApi.setButtonLoading(button, false);
    }
  });

  custodyNameInput.addEventListener('input', () => {
    if (!draft) return;
    draft.custodyName = custodyNameInput.value;
    if (draft.mode === 'edit') editorTitle.textContent = `تعديل: ${custodyNameInput.value || 'العهدة'}`;
    saveDraftSoon();
  });

  custodyDateInput.addEventListener('change', () => {
    if (!draft || draft.mode === 'edit') return;
    draft.custodyDate = custodyDateInput.value;
    saveDraftSoon();
  });

  addRowButton.addEventListener('click', () => {
    if (!draft) return;
    draft.items.push({
      productId: null,
      productName: '',
      unitName: '',
      quantity: null,
      packSize: null,
      unitCost: null,
      salePrice: null,
      note: '',
    });
    renderEditor();
    editorBody.lastElementChild?.querySelector('[data-field="productName"]')?.focus();
    saveDraftSoon();
  });

  discardButton.addEventListener('click', () => {
    if (!draft) return;

    if (draft.mode === 'edit') {
      if (!confirm('هل تريد إلغاء التعديلات غير المحفوظة؟')) return;
      removeStoredDraft();
      window.location.href = editReturnUrl();
      return;
    }

    if (!confirm('هل تريد إلغاء المسودة؟ العهد المحفوظة لن تتأثر.')) return;
    removeStoredDraft();
    draft = null;
    editorSection.hidden = true;
    draftNotice.hidden = true;
    VegApi.toast('تم إلغاء المسودة.');
  });

  saveButton.addEventListener('click', async () => {
    if (!draft) return;

    const custodyName = String(draft.custodyName || '').trim();
    if (custodyName.length < 2) {
      VegApi.toast('اكتب اسمًا واضحًا للعهدة.', 'error');
      custodyNameInput.focus();
      return;
    }

    if (!draft.custodyDate) {
      VegApi.toast('اختر تاريخ العهدة.', 'error');
      return;
    }

    if (!draft.items.length) {
      VegApi.toast('لا يمكن حفظ عهدة بدون أصناف.', 'error');
      return;
    }

    const emptyNameIndex = draft.items.findIndex((item) => !String(item.productName || '').trim());
    if (emptyNameIndex !== -1) {
      VegApi.toast(`اسم الصنف مطلوب في السطر ${emptyNameIndex + 1}.`, 'error');
      editorBody.querySelector(`tr[data-index="${emptyNameIndex}"] [data-field="productName"]`)?.focus();
      return;
    }

    const editing = draft.mode === 'edit';
    const confirmation = editing
      ? 'سيتم تحديث نفس العهدة، وسيبقى تاريخها الأصلي كما هو. هل أنت متأكد؟'
      : 'سيتم حفظ العهدة نهائيًا، وستُضاف الأصناف الجديدة إلى العهد القادمة. هل أنت متأكد؟';
    if (!confirm(confirmation)) return;

    VegApi.setButtonLoading(saveButton, true, editing ? 'جاري حفظ التعديلات...' : 'جاري الحفظ...');
    try {
      if (editing) {
        await VegApi.request(`/api/custodies/${draft.custodyId}`, {
          method: 'PUT',
          body: { custodyName, items: draft.items },
        });
      } else {
        await VegApi.request('/api/custodies', {
          method: 'POST',
          body: {
            requestId: draft.requestId,
            custodyName,
            custodyDate: draft.custodyDate,
            items: draft.items,
          },
        });
      }

      removeStoredDraft();
      const wasEditing = editing;
      draft = null;
      editorSection.hidden = true;
      draftNotice.hidden = true;
      VegApi.toast(wasEditing
        ? 'تم حفظ التعديلات دون تغيير تاريخ العهدة.'
        : 'تم حفظ العهدة والأصناف الجديدة بنجاح.');

      if (wasEditing && returnToFiles && user.permissions.includes('files')) {
        setTimeout(() => { window.location.href = '/app/files.html'; }, 500);
        return;
      }

      await loadCurrent();
      window.history.replaceState({}, '', '/app/custody.html');
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (error) {
      VegApi.toast(error.message, 'error');
    } finally {
      VegApi.setButtonLoading(saveButton, false);
    }
  });

  currentToggle.addEventListener('click', () => {
    const willOpen = currentToggle.getAttribute('aria-expanded') !== 'true';
    currentToggle.setAttribute('aria-expanded', String(willOpen));
    currentPanel.hidden = !willOpen;
  });

  newButton.addEventListener('click', startNew);

  await loadCurrent();

  if (Number.isInteger(requestedEditId) && requestedEditId > 0) {
    await startEdit(requestedEditId);
    return;
  }

  if (!canCreateCustody) {
    window.location.replace(user.permissions.includes('files') ? '/app/files.html' : '/app/');
    return;
  }

  const stored = localStorage.getItem(createStorageKey);
  if (stored) {
    try {
      const parsed = JSON.parse(stored);
      if (parsed?.createdForUser === user.id && parsed?.mode !== 'edit' && Array.isArray(parsed.items)) {
        draft = { ...parsed, mode: 'create' };
        if (!draft.requestId) draft.requestId = requestId();
        draftNotice.hidden = false;
        renderEditor();
      } else {
        localStorage.removeItem(createStorageKey);
      }
    } catch (_) {
      localStorage.removeItem(createStorageKey);
    }
  }
});
