// PPEQRTab.jsx — QR Code issuance + Admin approval (Supabase-powered)

const QR_INVENTORY_LIMIT = 12; // Show up to 12 most-relevant items as QR codes

const qrPpeStyles = {
  page: { padding: '0' },
  grid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 },
  card: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' },
  cardHeader: { padding: '13px 16px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  cardTitle: { fontSize: 14, fontWeight: 600, color: '#0F172A', fontFamily: "'Helvetica',sans-serif" },
  infoBox: { background: '#F0FDFA', border: '1px solid #99F6E4', borderRadius: 7, padding: '10px 14px', fontSize: 12, color: '#0F766E', marginBottom: 16, lineHeight: 1.6 },
  errorBox: { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 7, padding: '10px 14px', fontSize: 12, color: '#DC2626', marginBottom: 12, lineHeight: 1.5 },
  qrGrid: { display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 12, padding: 16, maxHeight: 580, overflowY: 'auto' },
  qrItem: { border: '1px solid #E2E8F0', borderRadius: 8, padding: '14px', textAlign: 'center', background: '#FAFCFF', transition: 'box-shadow 150ms' },
  qrItemName: { fontSize: 12, fontWeight: 600, color: '#0F172A', marginBottom: 2 },
  qrItemCat: { fontSize: 10, color: '#94A3B8', marginBottom: 10 },
  qrImg: { width: 110, height: 110, borderRadius: 6, border: '1px solid #E2E8F0', display: 'block', margin: '0 auto 10px' },
  qrActions: { display: 'flex', gap: 6, justifyContent: 'center' },
  dlBtn: { height: 26, padding: '0 10px', border: '1px solid #CBD5E1', borderRadius: 4, background: 'white', fontSize: 11, color: '#334155', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", fontWeight: 500 },
  scanBtn: { height: 26, padding: '0 10px', border: 'none', borderRadius: 4, background: '#0D9488', fontSize: 11, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", fontWeight: 600 },
  stockPill: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 4, fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 8 },
  reqList: { maxHeight: 580, overflowY: 'auto' },
  reqRow: { padding: '12px 16px', borderBottom: '1px solid #F1F5F9', display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, alignItems: 'center' },
  reqName: { fontSize: 13, fontWeight: 600, color: '#0F172A' },
  reqMeta: { fontSize: 11, color: '#94A3B8', marginTop: 2, lineHeight: 1.5 },
  reqItem: { fontSize: 12, color: '#475569', marginTop: 2 },
  approveBtn: { height: 28, padding: '0 12px', border: 'none', borderRadius: 5, background: '#16A34A', fontSize: 12, fontWeight: 600, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  rejectBtn: { height: 28, padding: '0 10px', border: '1px solid #CBD5E1', borderRadius: 5, background: 'white', fontSize: 12, color: '#64748B', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  pendingBadge: { display: 'inline-flex', padding: '2px 7px', borderRadius: 4, background: '#FEF3C7', color: '#92400E', fontSize: 10, fontWeight: 700, letterSpacing: '0.04em' },
  approvedBadge: { display: 'inline-flex', padding: '2px 7px', borderRadius: 4, background: '#F0FDF4', color: '#16A34A', fontSize: 10, fontWeight: 700, letterSpacing: '0.04em' },
  rejectedBadge: { display: 'inline-flex', padding: '2px 7px', borderRadius: 4, background: '#FEE2E2', color: '#991B1B', fontSize: 10, fontWeight: 700, letterSpacing: '0.04em' },
  emptyState: { padding: '40px 20px', textAlign: 'center', color: '#94A3B8', fontSize: 13 },
  // Scan modal (simulated phone view)
  overlay: { position: 'fixed', inset: 0, background: 'rgba(11,31,58,0.55)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  phone: { width: 340, background: '#F1F5F9', borderRadius: 28, overflow: 'hidden', boxShadow: '0 24px 64px rgba(0,0,0,0.25)', border: '6px solid #0B1F3A', maxHeight: '90vh', overflowY: 'auto' },
  phonebar: { background: '#0B1F3A', padding: '10px 20px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
  phoneBarText: { fontSize: 11, color: 'rgba(255,255,255,0.7)' },
  phoneBody: { background: 'white', padding: '20px 20px 24px' },
  phoneTitle: { fontFamily: "'Helvetica',sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 4 },
  phoneSub: { fontSize: 12, color: '#64748B', marginBottom: 16, lineHeight: 1.5 },
  phoneField: { marginBottom: 11 },
  phoneLabel: { fontSize: 11, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 4 },
  phoneInput: { width: '100%', height: 34, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 10px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: '#F8FAFC', boxSizing: 'border-box' },
  phoneSubmit: { width: '100%', height: 40, border: 'none', borderRadius: 8, background: '#0D9488', fontSize: 14, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", marginTop: 6 },
  phoneLogo: { display: 'flex', alignItems: 'center', gap: 7, marginBottom: 16, paddingBottom: 12, borderBottom: '1px solid #F1F5F9' },
};

const QR_DEPARTMENTS = ['Operations', 'Maintenance', 'Quality', 'HSE', 'Logistics', 'Production', 'Engineering', 'Warehouse'];

function fmtDateTime_QR(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleString('en-MY', { dateStyle: 'medium', timeStyle: 'short' }); }
  catch { return d; }
}

function StockPill({ status, balance }) {
  const map = {
    ok:       { bg: '#F0FDF4', color: '#16A34A', label: 'OK' },
    low:      { bg: '#FFFBEB', color: '#D97706', label: 'LOW' },
    critical: { bg: '#FFF5F5', color: '#DC2626', label: 'CRITICAL' },
  };
  const s = map[status] || map.ok;
  return <span style={{ ...qrPpeStyles.stockPill, background: s.bg, color: s.color }}>{s.label} · {balance ?? 0} avail</span>;
}

// ── Scan Modal (simulated phone) — submits to ppe_requests ──────────────────
function ScanModal({ item, accountId, onClose, onSubmitted }) {
  const [form, setForm] = React.useState({ empId: '', empName: '', dept: '', qty: 1, contact: '', reason: '' });
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [error, setError] = React.useState('');
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const valid = form.empId && form.empName && form.dept && form.contact && form.qty > 0;

  const handleSubmit = async () => {
    if (!valid) return;
    setBusy(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { error: insErr } = await sb.from('ppe_requests').insert({
        account_id:    accountId,
        emp_id:        form.empId.trim(),
        emp_name:      form.empName.trim(),
        department:    form.dept,
        contact:       form.contact.trim(),
        ppe_item_name: item.name + (item.size ? ` [${item.size}]` : ''),
        ppe_item_id:   item.id,
        qty:           Number(form.qty) || 1,
        status:        'pending',
      });
      if (insErr) throw insErr;
      setDone(true);
      setTimeout(() => onSubmitted?.(), 1500);
    } catch (err) {
      console.error('[QR Scan] error:', err);
      setError(err.message || 'Submission failed.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={qrPpeStyles.overlay} onClick={busy ? undefined : onClose}>
      <div style={qrPpeStyles.phone} onClick={e => e.stopPropagation()}>
        <div style={qrPpeStyles.phonebar}>
          <span style={qrPpeStyles.phoneBarText}>AegisComply · PPE Request</span>
          <span style={{ ...qrPpeStyles.phoneBarText, cursor: 'pointer' }} onClick={busy ? undefined : onClose}>✕</span>
        </div>
        <div style={qrPpeStyles.phoneBody}>
          {done ? (
            <div style={{ textAlign: 'center', padding: '16px 0' }}>
              <div style={{ width: 48, height: 48, borderRadius: '50%', background: '#F0FDF4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
              </div>
              <div style={{ fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 6 }}>Request Submitted!</div>
              <div style={{ fontSize: 12, color: '#64748B', lineHeight: 1.6 }}>Your PPE request for <strong>{item.name}</strong> has been sent to admin for approval. You will be notified once approved.</div>
            </div>
          ) : (
            <>
              <div style={qrPpeStyles.phoneLogo}>
                <img src="../../assets/logo-aegisfeld.png" style={{ width: 24, height: 24, objectFit: 'contain' }} alt="" onError={e => e.target.style.display='none'}/>
                <span style={{ fontFamily: "'Helvetica',sans-serif", fontSize: 14, fontWeight: 700, color: '#0B1F3A' }}>PPE Request Form</span>
              </div>
              <div style={qrPpeStyles.phoneTitle}>{item.name}{item.size ? ` [${item.size}]` : ''}</div>
              <div style={qrPpeStyles.phoneSub}>Fill in your details to request this PPE item. Admin approval required.</div>
              {error && <div style={{ background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 10px', fontSize: 11, color: '#DC2626', marginBottom: 10 }}>{error}</div>}
              <div style={qrPpeStyles.phoneField}><label style={qrPpeStyles.phoneLabel}>Employee ID *</label><input style={{ ...qrPpeStyles.phoneInput, fontFamily: "'JetBrains Mono',monospace", fontSize: 12 }} placeholder="EMP-0000" value={form.empId} onChange={e => set('empId', e.target.value)}/></div>
              <div style={qrPpeStyles.phoneField}><label style={qrPpeStyles.phoneLabel}>Full Name *</label><input style={qrPpeStyles.phoneInput} placeholder="Your full name" value={form.empName} onChange={e => set('empName', e.target.value)}/></div>
              <div style={qrPpeStyles.phoneField}><label style={qrPpeStyles.phoneLabel}>Department *</label><select style={qrPpeStyles.phoneInput} value={form.dept} onChange={e => set('dept', e.target.value)}><option value="">Select</option>{QR_DEPARTMENTS.map(d => <option key={d}>{d}</option>)}</select></div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <div style={qrPpeStyles.phoneField}><label style={qrPpeStyles.phoneLabel}>Quantity *</label><input type="number" min="1" style={qrPpeStyles.phoneInput} value={form.qty} onChange={e => set('qty', parseInt(e.target.value)||1)}/></div>
                <div style={qrPpeStyles.phoneField}><label style={qrPpeStyles.phoneLabel}>Contact No. *</label><input style={qrPpeStyles.phoneInput} placeholder="+60 1x-xxx xxxx" value={form.contact} onChange={e => set('contact', e.target.value)}/></div>
              </div>
              <button
                style={{ ...qrPpeStyles.phoneSubmit, background: (!valid || busy) ? '#CBD5E1' : '#0D9488', cursor: (!valid || busy) ? 'not-allowed' : 'pointer' }}
                onClick={handleSubmit}
                disabled={!valid || busy}
              >
                {busy ? 'Submitting…' : 'Submit Request'}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Main QR Tab ─────────────────────────────────────────────────────────────
function PPEQRTab({ user, isFrozen }) {
  const [inventory, setInventory]   = React.useState([]);
  const [requests, setRequests]     = React.useState([]);
  const [loading, setLoading]       = React.useState(false);
  const [error, setError]           = React.useState('');
  const [scanning, setScanning]     = React.useState(null);
  const [actingId, setActingId]     = React.useState(null);

  // Fetch all PPE inventory (no pagination — limit to 24 most relevant for QR display)
  const fetchInventory = React.useCallback(async () => {
    try {
      const sb = window.supabaseClient;
      // Prioritize low/critical items, then alphabetical — fetch all (Supabase default cap is 1000)
      const { data, error: qErr } = await sb.from('ppe_inventory')
        .select('*')
        .order('status', { ascending: false }) // critical first (alphabetically critical > low > ok)
        .order('name', { ascending: true });
      if (qErr) throw qErr;
      setInventory(data || []);
    } catch (err) {
      console.error('[QR Inventory] fetch error:', err);
      setError(err.message || 'Failed to load PPE.');
    }
  }, []);

  // Fetch PPE requests (account_id = current user)
  const fetchRequests = React.useCallback(async () => {
    setLoading(true);
    try {
      const sb = window.supabaseClient;
      const { data, error: qErr } = await sb.from('ppe_requests')
        .select('*')
        .order('submitted_at', { ascending: false })
        .limit(50);
      if (qErr) throw qErr;
      setRequests(data || []);
    } catch (err) {
      console.error('[QR Requests] fetch error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { fetchInventory(); fetchRequests(); }, [fetchInventory, fetchRequests]);

  // Realtime — react to new requests + status changes
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`qr-watcher-${user.id}`)
      .on('postgres_changes',
        { event: '*', schema: 'public', table: 'ppe_requests', filter: `account_id=eq.${user.id}` },
        () => { fetchRequests(); fetchInventory(); /* approval triggers inventory change too */ }
      )
      .on('postgres_changes',
        { event: '*', schema: 'public', table: 'ppe_inventory', filter: `user_id=eq.${user.id}` },
        () => { fetchInventory(); }
      )
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchInventory, fetchRequests]);

  // ── Approve / Reject ─────────────────────────────────────────────────────
  const handleApprove = async (req) => {
    if (isFrozen) return;
    setActingId(req.id);
    try {
      const sb = window.supabaseClient;
      const { error: upErr } = await sb.from('ppe_requests').update({
        status:      'approved',
        reviewed_at: new Date().toISOString(),
        reviewed_by: user.name || user.email,
      }).eq('id', req.id);
      if (upErr) throw upErr;
      // The DB trigger 'trigger_ppe_request_approved' handles stock deduction + issuance log
    } catch (err) {
      console.error('[QR Approve] error:', err);
      alert('Approval failed: ' + err.message);
    } finally {
      setActingId(null);
    }
  };

  const handleReject = async (req) => {
    if (isFrozen) return;
    setActingId(req.id);
    try {
      const sb = window.supabaseClient;
      const { error: upErr } = await sb.from('ppe_requests').update({
        status:      'rejected',
        reviewed_at: new Date().toISOString(),
        reviewed_by: user.name || user.email,
      }).eq('id', req.id);
      if (upErr) throw upErr;
    } catch (err) {
      console.error('[QR Reject] error:', err);
      alert('Rejection failed: ' + err.message);
    } finally {
      setActingId(null);
    }
  };

  const pendingCount = requests.filter(r => r.status === 'pending').length;

  return (
    <div style={qrPpeStyles.page}>
      <div style={{ ...qrPpeStyles.infoBox, margin: '0 0 16px' }}>
        <strong>How QR Issuance Works:</strong> Print or display each PPE item's QR code at your storage location. Workers scan the code with their phone, fill in their details, and submit. You review and approve — stock is deducted automatically on approval.
      </div>

      {error && <div style={qrPpeStyles.errorBox}>{error}</div>}

      <div style={qrPpeStyles.grid}>
        {/* QR Codes */}
        <div style={qrPpeStyles.card}>
          <div style={qrPpeStyles.cardHeader}>
            <span style={qrPpeStyles.cardTitle}>PPE QR Codes</span>
            <span style={{ fontSize: 11, color: '#94A3B8' }}>{inventory.length} items</span>
          </div>
          {inventory.length === 0 ? (
            <div style={qrPpeStyles.emptyState}>No PPE items yet. Add some in the Inventory tab.</div>
          ) : (
            <div style={qrPpeStyles.qrGrid}>
              {inventory.map((p) => {
                // Build QR URL with plain URL params (avoids Unicode/btoa issues)
                const qrTarget = `https://aegiscomply.my/ppe?account=${user?.id || ''}&item=${p.id}&code=${encodeURIComponent(p.item_code || '')}&name=${encodeURIComponent(p.name)}`;
                const qrData = encodeURIComponent(qrTarget);
                const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=110x110&data=${qrData}&color=0B1F3A`;
                return (
                  <div key={p.id} style={qrPpeStyles.qrItem}>
                    <StockPill status={p.status} balance={p.balance}/>
                    <img src={qrUrl} style={qrPpeStyles.qrImg} alt={`QR for ${p.name}`}/>
                    <div style={qrPpeStyles.qrItemName}>{p.name}{p.size ? ` [${p.size}]` : ''}</div>
                    <div style={qrPpeStyles.qrItemCat}>{p.item_code || '—'} · {p.category}</div>
                    <div style={qrPpeStyles.qrActions}>
                      <button style={qrPpeStyles.dlBtn} onClick={() => window.open(qrUrl.replace('110x110', '400x400'), '_blank')}>Print</button>
                      <button style={qrPpeStyles.scanBtn} onClick={() => setScanning(p)}>Simulate Scan</button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Approval Queue */}
        <div style={qrPpeStyles.card}>
          <div style={qrPpeStyles.cardHeader}>
            <span style={qrPpeStyles.cardTitle}>Approval Queue</span>
            {pendingCount > 0 && <span style={{ background: '#DC2626', color: 'white', fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 10 }}>{pendingCount} pending</span>}
          </div>
          <div style={qrPpeStyles.reqList}>
            {loading && requests.length === 0 && <div style={qrPpeStyles.emptyState}>Loading requests…</div>}
            {!loading && requests.length === 0 && (
              <div style={qrPpeStyles.emptyState}>No requests yet. Workers scan QR codes to submit requests.</div>
            )}
            {requests.map((req) => {
              const badgeStyle = req.status === 'approved' ? qrPpeStyles.approvedBadge
                              : req.status === 'rejected' ? qrPpeStyles.rejectedBadge
                              : qrPpeStyles.pendingBadge;
              return (
                <div key={req.id} style={qrPpeStyles.reqRow}>
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
                      <span style={qrPpeStyles.reqName}>{req.emp_name}</span>
                      <span style={badgeStyle}>{req.status.toUpperCase()}</span>
                    </div>
                    <div style={qrPpeStyles.reqMeta}>
                      <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, background: '#F1F5F9', padding: '1px 5px', borderRadius: 3, color: '#64748B' }}>{req.emp_id}</span>
                      &nbsp;· {req.department} · {req.contact}
                    </div>
                    <div style={qrPpeStyles.reqItem}>
                      <strong>{req.ppe_item_name}</strong> × {req.qty} &nbsp;·&nbsp; <span style={{ color: '#94A3B8' }}>{fmtDateTime_QR(req.submitted_at)}</span>
                    </div>
                    {req.reviewed_at && (
                      <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>
                        {req.status === 'approved' ? '✓' : '✗'} Reviewed by {req.reviewed_by || '—'} · {fmtDateTime_QR(req.reviewed_at)}
                      </div>
                    )}
                  </div>
                  {req.status === 'pending' && !isFrozen && (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                      <button
                        style={{ ...qrPpeStyles.approveBtn, opacity: actingId === req.id ? 0.6 : 1 }}
                        onClick={() => handleApprove(req)}
                        disabled={actingId === req.id}
                      >
                        {actingId === req.id ? '…' : 'Approve ✓'}
                      </button>
                      <button
                        style={qrPpeStyles.rejectBtn}
                        onClick={() => handleReject(req)}
                        disabled={actingId === req.id}
                      >
                        Reject
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {scanning && (
        <ScanModal
          item={scanning}
          accountId={user?.id}
          onClose={() => setScanning(null)}
          onSubmitted={() => { setScanning(null); fetchRequests(); }}
        />
      )}
    </div>
  );
}

Object.assign(window, { PPEQRTab });
