// CalibrationQRTab.jsx — QR Borrowing + Admin Approval (Supabase-powered)

const qrCalStyles = {
  page: { padding: 0 },
  grid: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 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 },
  devList: { overflowY: 'auto', maxHeight: 620 },
  devRow: { display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, padding: '12px 16px', borderBottom: '1px solid #F1F5F9', alignItems: 'center', transition: 'background 150ms' },
  devName: { fontSize: 13, fontWeight: 600, color: '#0F172A' },
  devSerial: { fontSize: 11, fontFamily: "'JetBrains Mono',monospace", color: '#94A3B8', marginTop: 1 },
  devActions: { display: 'flex', gap: 6, alignItems: 'center' },
  qrThumb: { width: 44, height: 44, border: '1px solid #E2E8F0', borderRadius: 6 },
  scanBtn: { height: 26, padding: '0 10px', border: 'none', borderRadius: 4, background: '#0B1F3A', fontSize: 11, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", fontWeight: 600 },
  printBtn: { height: 26, padding: '0 10px', border: '1px solid #CBD5E1', borderRadius: 4, background: 'white', fontSize: 11, color: '#334155', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  statusDot: { width: 7, height: 7, borderRadius: '50%', display: 'inline-block', marginRight: 5 },
  reqList: { maxHeight: 620, overflowY: 'auto' },
  reqRow: { padding: '12px 16px', borderBottom: '1px solid #F1F5F9' },
  reqHead: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 4 },
  reqName: { fontSize: 13, fontWeight: 600, color: '#0F172A' },
  reqMeta: { fontSize: 11, color: '#94A3B8', lineHeight: 1.7 },
  reqDevice: { fontSize: 12, color: '#334155', marginTop: 3, fontWeight: 500 },
  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 },
  approvedBadge: { display: 'inline-flex', padding: '2px 7px', borderRadius: 4, background: '#F0FDF4', color: '#16A34A', fontSize: 10, fontWeight: 700 },
  rejectedBadge: { display: 'inline-flex', padding: '2px 7px', borderRadius: 4, background: '#FEE2E2', color: '#991B1B', fontSize: 10, fontWeight: 700 },
  empty: { padding: '40px 20px', textAlign: 'center', color: '#94A3B8', fontSize: 13 },
  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: '18px 18px 22px' },
  phoneTitle: { fontFamily: "'Helvetica',sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 3 },
  phoneSub: { fontSize: 12, color: '#64748B', marginBottom: 14, lineHeight: 1.5 },
  phoneField: { marginBottom: 10 },
  phoneLabel: { fontSize: 11, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 3 },
  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: 14, paddingBottom: 10, borderBottom: '1px solid #F1F5F9' },
  deviceInfoBox: { background: '#F0F7FC', border: '1px solid #B3D1E8', borderRadius: 6, padding: '8px 12px', marginBottom: 12, fontSize: 12 },
};

const BORROW_DEPARTMENTS = ['Operations', 'Maintenance', 'Quality', 'HSE', 'Logistics', 'Production', 'Engineering', 'Warehouse'];
const BORROW_DURATIONS   = ['4 hours', '1 day', '2 days', '3 days', '1 week', 'Custom'];

const borrowStatusColors = {
  active:              { dot: '#16A34A', label: 'Active' },
  valid:               { dot: '#16A34A', label: 'Active' },
  expiring:            { dot: '#D97706', label: 'Expiring' },
  overdue:             { dot: '#EA580C', label: 'Overdue' },
  expired:             { dot: '#DC2626', label: 'Expired' },
  pending_calibration: { dot: '#475569', label: 'At Lab' },
};

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

// ── Borrow Modal (simulated phone) ──────────────────────────────────────────
function BorrowModal({ device, accountId, onClose, onSubmitted }) {
  const [form, setForm] = React.useState({ name: '', dept: '', contact: '', duration: '1 day', 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.name && form.dept && form.contact;

  const handleSubmit = async () => {
    if (!valid) return;
    setBusy(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { error: insErr } = await sb.from('borrow_requests').insert({
        account_id:     accountId,
        requester_name: form.name.trim(),
        department:     form.dept,
        contact:        form.contact.trim(),
        duration:       form.duration,
        reason:         form.reason || null,
        device_name:    device.name,
        serial_number:  device.serial_number,
        equipment_id:   device.id,
        status:         'pending',
      });
      if (insErr) throw insErr;
      setDone(true);
      setTimeout(() => onSubmitted?.(), 1500);
    } catch (err) {
      console.error('[Borrow] error:', err);
      setError(err.message || 'Submission failed.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={qrCalStyles.overlay} onClick={busy ? undefined : onClose}>
      <div style={qrCalStyles.phone} onClick={e => e.stopPropagation()}>
        <div style={qrCalStyles.phonebar}>
          <span style={qrCalStyles.phoneBarText}>AegisComply · Equipment Borrow</span>
          <span style={{ ...qrCalStyles.phoneBarText, cursor: 'pointer' }} onClick={busy ? undefined : onClose}>✕</span>
        </div>
        <div style={qrCalStyles.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 borrowing request for <strong>{device.name}</strong> is pending admin approval.</div>
            </div>
          ) : (
            <>
              <div style={qrCalStyles.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' }}>Equipment Borrow Request</span>
              </div>
              <div style={qrCalStyles.deviceInfoBox}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#0F172A' }}>{device.name}</div>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: '#64748B', marginTop: 2 }}>{device.serial_number}</div>
              </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={qrCalStyles.phoneField}><label style={qrCalStyles.phoneLabel}>Your Full Name *</label><input style={qrCalStyles.phoneInput} placeholder="Full name" value={form.name} onChange={e => set('name', e.target.value)}/></div>
              <div style={qrCalStyles.phoneField}><label style={qrCalStyles.phoneLabel}>Department *</label>
                <select style={qrCalStyles.phoneInput} value={form.dept} onChange={e => set('dept', e.target.value)}>
                  <option value="">Select</option>
                  {BORROW_DEPARTMENTS.map(d => <option key={d}>{d}</option>)}
                </select>
              </div>
              <div style={qrCalStyles.phoneField}><label style={qrCalStyles.phoneLabel}>Contact Number *</label><input style={qrCalStyles.phoneInput} placeholder="+60 1x-xxx xxxx" value={form.contact} onChange={e => set('contact', e.target.value)}/></div>
              <div style={qrCalStyles.phoneField}><label style={qrCalStyles.phoneLabel}>Estimated Duration *</label>
                <select style={qrCalStyles.phoneInput} value={form.duration} onChange={e => set('duration', e.target.value)}>
                  {BORROW_DURATIONS.map(d => <option key={d}>{d}</option>)}
                </select>
              </div>
              <div style={qrCalStyles.phoneField}><label style={qrCalStyles.phoneLabel}>Purpose / Reason</label><input style={qrCalStyles.phoneInput} placeholder="Brief reason for borrowing" value={form.reason} onChange={e => set('reason', e.target.value)}/></div>
              <button
                style={{ ...qrCalStyles.phoneSubmit, background: (!valid || busy) ? '#CBD5E1' : '#0D9488', cursor: (!valid || busy) ? 'not-allowed' : 'pointer' }}
                onClick={handleSubmit}
                disabled={!valid || busy}
              >
                {busy ? 'Submitting…' : 'Submit Borrow Request'}
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Main QR Borrowing Tab ───────────────────────────────────────────────────
function CalibrationQRTab({ user, isFrozen }) {
  const [equipment, setEquipment] = 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);
  const [hovered, setHovered]     = React.useState(null);

  const fetchEquipment = React.useCallback(async () => {
    try {
      const sb = window.supabaseClient;
      const { data, error: qErr } = await sb.from('equipment').select('id,name,serial_number,department,status').order('name');
      if (qErr) throw qErr;
      setEquipment(data || []);
    } catch (err) {
      console.error('[Borrow Equipment] fetch error:', err);
      setError(err.message || 'Failed to load equipment.');
    }
  }, []);

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

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

  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`borrow-watcher-${user.id}`)
      .on('postgres_changes',
        { event: '*', schema: 'public', table: 'borrow_requests', filter: `account_id=eq.${user.id}` },
        () => { fetchRequests(); }
      )
      .on('postgres_changes',
        { event: '*', schema: 'public', table: 'equipment', filter: `user_id=eq.${user.id}` },
        () => { fetchEquipment(); }
      )
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchEquipment, fetchRequests]);

  const handleApprove = async (req) => {
    if (isFrozen) return;
    setActingId(req.id);
    try {
      const sb = window.supabaseClient;
      const { error: upErr } = await sb.from('borrow_requests').update({
        status:      'approved',
        reviewed_at: new Date().toISOString(),
        reviewed_by: user.name || user.email,
      }).eq('id', req.id);
      if (upErr) throw upErr;
    } catch (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('borrow_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) {
      alert('Rejection failed: ' + err.message);
    } finally {
      setActingId(null);
    }
  };

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

  return (
    <div style={qrCalStyles.page}>
      <div style={{ ...qrCalStyles.infoBox, margin: '0 0 16px' }}>
        <strong>Equipment Borrowing via QR:</strong> Attach a QR code to each piece of equipment. Workers scan to submit a borrowing request including their name, department, contact number, and estimated duration. Admin reviews and approves — full audit trail maintained.
      </div>

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

      <div style={qrCalStyles.grid}>
        {/* Device QR list */}
        <div style={qrCalStyles.card}>
          <div style={qrCalStyles.cardHeader}>
            <span style={qrCalStyles.cardTitle}>Equipment QR Codes</span>
            <span style={{ fontSize: 11, color: '#94A3B8' }}>{equipment.length} items</span>
          </div>
          <div style={qrCalStyles.devList}>
            {equipment.length === 0 ? (
              <div style={qrCalStyles.empty}>No equipment yet. Add equipment on the Equipment page.</div>
            ) : equipment.map((eq, i) => {
              const qrTarget = `https://aegiscomply.my/borrow?account=${user?.id || ''}&id=${eq.id}&device=${encodeURIComponent(eq.name)}&serial=${encodeURIComponent(eq.serial_number)}`;
              const qrData   = encodeURIComponent(qrTarget);
              const qrUrl    = `https://api.qrserver.com/v1/create-qr-code/?size=44x44&data=${qrData}&color=0B1F3A`;
              const sc = borrowStatusColors[eq.status] || borrowStatusColors.active;
              return (
                <div key={eq.id} style={{ ...qrCalStyles.devRow, background: hovered === i ? '#F8FAFC' : 'white' }} onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                      <span style={{ ...qrCalStyles.statusDot, background: sc.dot }}/>
                      <span style={qrCalStyles.devName}>{eq.name}</span>
                    </div>
                    <div style={qrCalStyles.devSerial}>{eq.serial_number}{eq.department ? ` · ${eq.department}` : ''}</div>
                  </div>
                  <div style={qrCalStyles.devActions}>
                    <img src={qrUrl} style={qrCalStyles.qrThumb} alt="QR" title="Scan to borrow"/>
                    <button style={qrCalStyles.printBtn} onClick={() => window.open(qrUrl.replace('44x44', '400x400'), '_blank')}>Print</button>
                    <button style={qrCalStyles.scanBtn} onClick={() => setScanning(eq)}>Scan</button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Borrow approval queue */}
        <div style={qrCalStyles.card}>
          <div style={qrCalStyles.cardHeader}>
            <span style={qrCalStyles.cardTitle}>Borrow Requests</span>
            {pending > 0 && <span style={{ background: '#DC2626', color: 'white', fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 10 }}>{pending} pending</span>}
          </div>
          <div style={qrCalStyles.reqList}>
            {loading && requests.length === 0 && <div style={qrCalStyles.empty}>Loading…</div>}
            {!loading && requests.length === 0 && <div style={qrCalStyles.empty}>No borrow requests yet. Workers scan QR codes to submit.</div>}
            {requests.map((req) => {
              const badgeStyle = req.status === 'approved' ? qrCalStyles.approvedBadge
                              : req.status === 'rejected' ? qrCalStyles.rejectedBadge
                              : qrCalStyles.pendingBadge;
              return (
                <div key={req.id} style={qrCalStyles.reqRow}>
                  <div style={qrCalStyles.reqHead}>
                    <div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                        <span style={qrCalStyles.reqName}>{req.requester_name}</span>
                        <span style={badgeStyle}>{req.status.toUpperCase()}</span>
                      </div>
                      <div style={qrCalStyles.reqMeta}>
                        {req.department} · {req.contact} · Duration: <strong>{req.duration}</strong>
                      </div>
                      <div style={qrCalStyles.reqDevice}>
                        {req.device_name}
                        <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: '#94A3B8', marginLeft: 6 }}>{req.serial_number}</span>
                      </div>
                      {req.reason && <div style={{ fontSize: 11, color: '#64748B', marginTop: 2 }}>Reason: {req.reason}</div>}
                      <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 3 }}>{qrFmtDateTime(req.submitted_at)}</div>
                      {req.reviewed_at && (
                        <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>
                          {req.status === 'approved' ? '✓' : '✗'} Reviewed by {req.reviewed_by || '—'} · {qrFmtDateTime(req.reviewed_at)}
                        </div>
                      )}
                    </div>
                    {req.status === 'pending' && !isFrozen && (
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 5, flexShrink: 0 }}>
                        <button
                          style={{ ...qrCalStyles.approveBtn, opacity: actingId === req.id ? 0.6 : 1 }}
                          onClick={() => handleApprove(req)}
                          disabled={actingId === req.id}
                        >
                          {actingId === req.id ? '…' : 'Approve ✓'}
                        </button>
                        <button
                          style={qrCalStyles.rejectBtn}
                          onClick={() => handleReject(req)}
                          disabled={actingId === req.id}
                        >
                          Reject
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

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

Object.assign(window, { CalibrationQRTab });
