import * as store from '../../../core/store.js';
import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as bus from '../../../core/bus.js';
import * as net from '../../../core/net.js';
import { emoji } from '../../../core/theme.js';

const DOC_TYPES = [
  { value: 'membership_card', label: 'بطاقة عضوية' },
  { value: 'id_card', label: 'بطاقة هوية' },
  { value: 'receipt', label: 'إيصال دفع' },
  { value: 'other', label: 'أخرى' }
];

export async function mountOrgApply(el) {
  el.innerHTML = `
    <div style="padding:var(--s-4);display:flex;flex-direction:column;gap:var(--s-4);padding-bottom:max(var(--s-4), env(safe-area-inset-bottom));">
      <div style="display:flex;align-items:center;gap:var(--s-3);">
        <button id="btn-back" class="btn btn-secondary" style="min-width:40px;min-height:40px;padding:0;display:flex;align-items:center;justify-content:center;">
          ${emoji('arrow_back', '←', 18)}
        </button>
        <div style="font-size:18px;font-weight:700;">الانضمام لمنظمة</div>
      </div>
      <div id="org-content" style="display:flex;flex-direction:column;gap:var(--s-3);">
        <div style="text-align:center;padding:var(--s-6);color:var(--text-secondary);">جاري التحميل...</div>
      </div>
    </div>
  `;

  el.querySelector('#btn-back').addEventListener('click', () => {
    audio.play('click');
    scene.pop();
  });

  await loadOrgs(el);
}

async function loadOrgs(el) {
  const content = el.querySelector('#org-content');

  try {
    const [orgs, memberships, applications] = await Promise.all([
      net.post('profile.php', { action: 'get-orgs' }),
      net.post('profile.php', { action: 'my-memberships' }),
      net.post('profile.php', { action: 'my-applications' })
    ]);

    if (!orgs || !Array.isArray(orgs) || orgs.length === 0) {
      content.innerHTML = `<div class="card" style="text-align:center;padding:var(--s-6);color:var(--text-secondary);">لا توجد منظمات متاحة حالياً</div>`;
      return;
    }

    const memberOrgIds = new Set(
      (Array.isArray(memberships) ? memberships : [])
        .filter(m => m.status === 'active')
        .map(m => m.organization_id)
    );

    const appMap = {};
    (Array.isArray(applications) ? applications : []).forEach(app => {
      if (!appMap[app.org_id] || new Date(app.created_at) > new Date(appMap[app.org_id].created_at)) {
        appMap[app.org_id] = app;
      }
    });

    content.innerHTML = orgs.map(org => {
      const isMember = memberOrgIds.has(org.id);
      const app = appMap[org.id];
      let badge = '';
      let actionBtn = '';

      if (isMember) {
        badge = `<span style="background:var(--success);color:#fff;font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;">${emoji('check', '✓', 12)} عضو</span>`;
      } else if (app && app.status === 'pending') {
        badge = `<span style="background:#f59e0b;color:#000;font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;">قيد المراجعة</span>`;
      } else if (app && app.status === 'rejected') {
        badge = `<span style="background:var(--error);color:#fff;font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;">مرفوض</span>`;
        if (app.rejection_reason) {
          badge += `<div style="font-size:11px;color:var(--error);margin-top:4px;">السبب: ${escHtml(app.rejection_reason)}</div>`;
        }
        actionBtn = `<button class="btn btn-primary btn-apply" data-org-id="${org.id}" style="min-height:36px;font-size:13px;margin-top:var(--s-2);">إعادة التقديم</button>`;
      } else {
        actionBtn = `<button class="btn btn-primary btn-apply" data-org-id="${org.id}" style="min-height:36px;font-size:13px;margin-top:var(--s-2);">تقديم طلب</button>`;
      }

      const logoHtml = org.logo_url
        ? `<img src="${org.logo_url}" style="width:40px;height:40px;border-radius:8px;object-fit:contain;" alt="">`
        : `<div style="width:40px;height:40px;border-radius:8px;background:var(--bg-elevated);display:flex;align-items:center;justify-content:center;">${emoji('building', '🏢', 20)}</div>`;

      return `
        <div class="card" style="padding:var(--s-3);">
          <div style="display:flex;align-items:center;gap:var(--s-3);">
            ${logoHtml}
            <div style="flex:1;min-width:0;">
              <div style="font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${escHtml(org.name)}</div>
              ${org.country_code ? `<div style="font-size:12px;color:var(--text-secondary);">${org.country_code}</div>` : ''}
            </div>
            <div style="text-align:center;">${badge}</div>
          </div>
          ${actionBtn}
        </div>
      `;
    }).join('');

    // Apply button handlers
    content.querySelectorAll('.btn-apply').forEach(btn => {
      btn.addEventListener('click', () => {
        audio.play('click');
        const orgId = btn.dataset.orgId;
        const org = orgs.find(o => o.id === orgId);
        showApplyForm(el, org, content);
      });
    });

  } catch (err) {
    content.innerHTML = `<div class="card" style="text-align:center;padding:var(--s-4);color:var(--error);">فشل تحميل المنظمات: ${escHtml(err.message)}</div>`;
  }
}

function showApplyForm(el, org, contentParent) {
  const content = el.querySelector('#org-content');

  content.innerHTML = `
    <div class="card" style="padding:var(--s-4);">
      <div style="font-size:15px;font-weight:600;margin-bottom:var(--s-3);">تقديم طلب انضمام — ${escHtml(org.name)}</div>

      <div style="display:flex;flex-direction:column;gap:var(--s-3);">
        <div>
          <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">نوع المستند</label>
          <select id="apply-doc-type"
            style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;">
            ${DOC_TYPES.map(d => `<option value="${d.value}">${d.label}</option>`).join('')}
          </select>
        </div>

        <div>
          <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">ملاحظات (اختياري)</label>
          <textarea id="apply-notes" maxlength="500" dir="auto" rows="3"
            style="background:#1e1e3a;border:1px solid rgba(255,255,255,0.1);color:#f8fafc;border-radius:8px;padding:10px 12px;font-size:14px;font-family:inherit;width:100%;box-sizing:border-box;resize:vertical;"
            placeholder="رسالة لإدارة المنظمة..."></textarea>
        </div>

        <div>
          <label style="font-size:13px;color:var(--text-secondary);margin-bottom:4px;display:block;">صورة إثبات</label>
          <div id="upload-area" style="background:#1e1e3a;border:2px dashed rgba(255,255,255,0.15);border-radius:8px;padding:var(--s-4);text-align:center;cursor:pointer;">
            <div id="upload-placeholder">
              <div>${emoji('camera', '📷', 28)}</div>
              <div style="font-size:13px;color:var(--text-secondary);margin-top:var(--s-2);">اضغط لاختيار صورة</div>
              <div style="font-size:11px;color:var(--text-secondary);">PNG, JPG, WebP — حد أقصى 5MB</div>
            </div>
            <div id="upload-preview" style="display:none;">
              <img id="preview-img" style="max-width:100%;max-height:200px;border-radius:6px;object-fit:contain;">
            </div>
          </div>
          <input type="file" id="apply-file" accept="image/jpeg,image/png,image/webp" style="display:none;">
        </div>

        <div style="display:flex;gap:var(--s-3);margin-top:var(--s-2);">
          <button id="btn-cancel-apply" class="btn btn-secondary" style="flex:1;min-height:44px;">إلغاء</button>
          <button id="btn-submit-apply" class="btn btn-primary" style="flex:1;min-height:44px;font-weight:700;">إرسال الطلب</button>
        </div>
      </div>
    </div>
  `;

  let selectedFile = null;

  // Upload area click
  const uploadArea = content.querySelector('#upload-area');
  const fileInput = content.querySelector('#apply-file');

  uploadArea.addEventListener('click', () => {
    fileInput.click();
  });

  fileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) {
      bus.emit('toast', { text: 'حجم الملف أكبر من 5MB', type: 'error' });
      return;
    }
    selectedFile = file;
    const reader = new FileReader();
    reader.onload = (ev) => {
      content.querySelector('#upload-placeholder').style.display = 'none';
      const preview = content.querySelector('#upload-preview');
      preview.style.display = 'block';
      content.querySelector('#preview-img').src = ev.target.result;
    };
    reader.readAsDataURL(file);
  });

  // Cancel
  content.querySelector('#btn-cancel-apply').addEventListener('click', () => {
    audio.play('click');
    loadOrgs(el);
  });

  // Submit
  content.querySelector('#btn-submit-apply').addEventListener('click', async () => {
    audio.play('click');
    const docType = content.querySelector('#apply-doc-type').value;
    const notes = content.querySelector('#apply-notes').value.trim();
    const btn = content.querySelector('#btn-submit-apply');

    btn.disabled = true;
    btn.style.opacity = '0.6';
    btn.textContent = 'جاري الإرسال...';

    try {
      const formData = new FormData();
      formData.append('org_id', org.id);
      formData.append('document_type', docType);
      formData.append('notes', notes);

      if (selectedFile) {
        const compressed = await compressProofImage(selectedFile);
        formData.append('proof_document', compressed, 'proof.' + getExt(selectedFile));
      }

      const token = store.get('auth.token');
      const res = await fetch('/api/org-apply.php', {
        method: 'POST',
        headers: { 'Authorization': `Bearer ${token}` },
        body: formData
      });

      const data = await res.json();
      if (!res.ok || data.error) {
        throw new Error(data.error || 'فشل إرسال الطلب');
      }

      bus.emit('toast', { text: 'تم إرسال الطلب بنجاح', type: 'success' });
      await loadOrgs(el);
    } catch (err) {
      bus.emit('toast', { text: err.message || 'فشل إرسال الطلب', type: 'error' });
      btn.disabled = false;
      btn.style.opacity = '1';
      btn.textContent = 'إرسال الطلب';
    }
  });
}

function compressProofImage(file) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      const maxDim = 1200;
      let w = img.width;
      let h = img.height;
      if (w > maxDim || h > maxDim) {
        if (w > h) { h = Math.round(h * maxDim / w); w = maxDim; }
        else { w = Math.round(w * maxDim / h); h = maxDim; }
      }
      const canvas = document.createElement('canvas');
      canvas.width = w;
      canvas.height = h;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, w, h);
      canvas.toBlob(
        (blob) => blob ? resolve(blob) : reject(new Error('Compression failed')),
        'image/jpeg',
        0.8
      );
      URL.revokeObjectURL(img.src);
    };
    img.onerror = () => { URL.revokeObjectURL(img.src); reject(new Error('Invalid image')); };
    img.src = URL.createObjectURL(file);
  });
}

function getExt(file) {
  const type = file.type;
  if (type === 'image/png') return 'png';
  if (type === 'image/webp') return 'webp';
  return 'jpg';
}

function escHtml(str) {
  return String(str || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
