// admin-verification-review.jsx — Admin drawer for reviewing a tutor's
// submitted verification + approving / rejecting it.
//
// Opens from admin-instructors.jsx when the admin clicks the "Submitted —
// review" pill on a row. Loads the instructor_verifications row (sensitive
// columns are admin-readable except for the ciphertext byteas — those come
// from admin_decrypt_verification() which audit-logs).

const AVR_NAVY  = 'oklch(22% 0.06 265)';
const AVR_GOLD  = 'oklch(72% 0.17 80)';
const AVR_PAPER = 'oklch(98% 0.008 60)';
const AVR_BORDER = 'oklch(88% 0.02 265)';
const AVR_MUTED = 'oklch(58% 0.03 265)';
const AVR_INK   = 'oklch(18% 0.03 265)';

const AVRBlock = ({ title, status, children }) => (
  <div style={{ background:'#fff', border:`1px solid ${AVR_BORDER}`, borderRadius:10, padding:'14px 16px', marginBottom:12 }}>
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
      <span style={{ fontSize:11, fontWeight:700, letterSpacing:'0.08em', color:AVR_MUTED, textTransform:'uppercase' }}>{title}</span>
      {status === 'done' && <span style={{ fontSize:11, color:'oklch(36% 0.13 150)', fontWeight:700 }}>✓ submitted</span>}
      {status === 'not_requested' && <span style={{ fontSize:11, color:AVR_MUTED }}>not requested</span>}
      {status === 'pending' && <span style={{ fontSize:11, color:'oklch(50% 0.12 80)', fontWeight:700 }}>pending</span>}
    </div>
    <div style={{ fontSize:14, color:AVR_INK, lineHeight:1.6 }}>{children}</div>
  </div>
);

const AVRField = ({ label, value }) => (
  <div style={{ display:'flex', gap:14, padding:'4px 0' }}>
    <span style={{ width:120, fontSize:12, fontWeight:600, color:AVR_MUTED, flexShrink:0 }}>{label}</span>
    <span style={{ fontSize:13, color:AVR_INK, wordBreak:'break-word' }}>{value || <span style={{ color:AVR_MUTED, fontStyle:'italic' }}>—</span>}</span>
  </div>
);

const AVRRevealRow = ({ label, masked, revealed, busy, onReveal, isVisible }) => (
  <div style={{ display:'flex', gap:14, padding:'4px 0', alignItems:'center', flexWrap:'wrap' }}>
    <span style={{ width:120, fontSize:12, fontWeight:600, color:AVR_MUTED, flexShrink:0 }}>{label}</span>
    {isVisible && revealed ? (
      <span style={{ fontSize:14, color:AVR_INK, fontVariantNumeric:'tabular-nums', fontWeight:700, background:'oklch(96% 0.05 80)', padding:'3px 8px', borderRadius:6, letterSpacing:'0.04em' }}>
        {revealed}
      </span>
    ) : (
      <>
        <span style={{ fontSize:14, color:AVR_INK, fontVariantNumeric:'tabular-nums' }}>{masked || '—'}</span>
        {masked && (
          <button onClick={onReveal} disabled={busy}
            style={{ background:'oklch(96% 0.04 265)', border:`1px solid ${AVR_BORDER}`, borderRadius:6, padding:'4px 10px', fontSize:11, fontWeight:700, color:AVR_NAVY, cursor: busy ? 'wait' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
            {busy ? 'Revealing…' : '🔓 Reveal'}
          </button>
        )}
      </>
    )}
  </div>
);

const AdminVerificationReview = ({ instructor, onClose }) => {
  const [iv, setIv]         = React.useState(null);
  const [loading, setLoad]  = React.useState(true);
  const [decrypted, setDec] = React.useState(null);   // { ssn, dob, bank_routing, bank_account }
  const [reveal, setReveal] = React.useState(false);   // toggles visibility of the decrypted values
  const [revealBusy, setRB] = React.useState(false);
  const [govUrl, setGovUrl] = React.useState(null);
  const [busy, setBusy]     = React.useState(false);
  const [error, setError]   = React.useState('');
  const [rejectMode, setRej] = React.useState(false);
  const [reason, setReason] = React.useState('');

  const load = React.useCallback(async () => {
    setLoad(true);
    const { data, error: e } = await window.supa
      .from('instructor_verifications').select('*').eq('instructor_id', instructor.id).maybeSingle();
    if (e) console.warn('[avr] load:', e.message);
    setIv(data || null);
    setLoad(false);
    if (data?.gov_id_storage_path) {
      try {
        const { data: signed } = await window.supa.storage.from('instructor-gov-ids')
          .createSignedUrl(data.gov_id_storage_path, 600);
        if (signed?.signedUrl) setGovUrl(signed.signedUrl);
      } catch (err) { console.warn('[avr] signed url:', err.message); }
    }
  }, [instructor.id]);

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

  // Auto-hide revealed values after 60 seconds.
  React.useEffect(() => {
    if (!reveal) return;
    const t = setTimeout(() => { setReveal(false); }, 60000);
    return () => clearTimeout(t);
  }, [reveal]);

  const doReveal = async () => {
    if (decrypted) { setReveal(true); return; }
    setRB(true); setError('');
    try {
      const { data, error: e } = await window.supa.rpc('admin_decrypt_verification', { p_instructor_id: instructor.id });
      if (e) throw e;
      const row = Array.isArray(data) ? data[0] : data;
      if (!row) throw new Error('No data returned.');
      setDec(row);
      setReveal(true);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not reveal') : (e.message || 'Could not reveal'));
    } finally { setRB(false); }
  };

  const approve = async () => {
    if (!confirm(`Approve ${instructor.name}'s verification? They'll be emailed immediately.`)) return;
    setBusy(true); setError('');
    try {
      const { error: e } = await window.supa.rpc('admin_approve_verification', { p_instructor_id: instructor.id });
      if (e) throw e;
      await load();
      onClose && onClose();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not approve') : (e.message || 'Could not approve'));
    } finally { setBusy(false); }
  };

  const reject = async () => {
    if (reason.trim().length < 4) { setError('Please write a short reason.'); return; }
    setBusy(true); setError('');
    try {
      const { error: e } = await window.supa.rpc('admin_reject_verification', { p_instructor_id: instructor.id, p_reason: reason.trim() });
      if (e) throw e;
      await load();
      onClose && onClose();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not reject') : (e.message || 'Could not reject'));
    } finally { setBusy(false); }
  };

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.45)', display:'flex', justifyContent:'flex-end', zIndex:9000 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:540, maxWidth:'100%', background:AVR_PAPER, height:'100%', boxShadow:'-10px 0 40px rgba(0,0,0,0.25)', overflowY:'auto', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <div style={{ position:'sticky', top:0, background:'#fff', borderBottom:`1px solid ${AVR_BORDER}`, padding:'16px 24px', display:'flex', justifyContent:'space-between', alignItems:'center', zIndex:5 }}>
          <div>
            <div style={{ fontSize:11, fontWeight:700, color:AVR_GOLD, textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:3 }}>Review verification</div>
            <div style={{ fontSize:18, fontWeight:700, color:AVR_INK }}>{instructor.name}</div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background:'none', border:'none', fontSize:22, color:AVR_MUTED, cursor:'pointer', lineHeight:1 }}>×</button>
        </div>

        <div style={{ padding:'20px 24px 40px' }}>
          {loading && <div style={{ color:AVR_MUTED, fontSize:13 }}>Loading…</div>}

          {!loading && !iv && (
            <div style={{ padding:'24px', background:'#fff', borderRadius:10, border:`1px solid ${AVR_BORDER}`, fontSize:13, color:AVR_MUTED }}>
              No verification record on file for this instructor.
            </div>
          )}

          {!loading && iv && (
            <>
              {/* Status line */}
              <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14, flexWrap:'wrap' }}>
                <span style={{ fontSize:11, fontWeight:700, padding:'4px 10px', borderRadius:20, textTransform:'uppercase', letterSpacing:'0.05em',
                  ...(iv.status === 'submitted' ? { background:'oklch(96% 0.07 80)',  color:'oklch(34% 0.14 80)' }
                    : iv.status === 'approved'   ? { background:'oklch(94% 0.07 150)', color:'oklch(30% 0.13 150)' }
                    : iv.status === 'rejected'   ? { background:'oklch(95% 0.06 25)',  color:'oklch(40% 0.15 25)'  }
                    : iv.status === 'in_progress'? { background:'oklch(96% 0.05 265)', color:'oklch(28% 0.1 265)'  }
                    : { background:'oklch(96% 0.005 265)', color: AVR_MUTED }) }}>
                  {iv.status.replace('_',' ')}
                </span>
                {iv.submitted_at && <span style={{ fontSize:12, color:AVR_MUTED }}>submitted {new Date(iv.submitted_at).toLocaleString()}</span>}
              </div>

              {iv.admin_message && (
                <div style={{ background:'oklch(97% 0.025 80)', border:`1px solid ${AVR_GOLD}`, borderRadius:10, padding:'10px 14px', marginBottom:14, fontSize:13, color:'oklch(28% 0.07 80)', fontStyle:'italic' }}>
                  Note sent to instructor: "{iv.admin_message}"
                </div>
              )}

              {/* Identity */}
              {iv.requested_fields?.includes('identity') && (
                <AVRBlock title="Identity" status={iv.identity_completed_at ? 'done' : 'pending'}>
                  <AVRField label="Legal name" value={[iv.legal_first_name, iv.legal_middle_name, iv.legal_last_name].filter(Boolean).join(' ')} />
                  <AVRRevealRow label="Date of birth"
                    masked={iv.identity_completed_at ? '••• encrypted' : null}
                    revealed={decrypted?.dob ? new Date(decrypted.dob).toLocaleDateString() : null}
                    isVisible={reveal} onReveal={doReveal} busy={revealBusy} />
                  <AVRRevealRow label="SSN"
                    masked={iv.ssn_last_four ? `••• ••• ${iv.ssn_last_four}` : null}
                    revealed={decrypted?.ssn ? formatSSNFull(decrypted.ssn) : null}
                    isVisible={reveal} onReveal={doReveal} busy={revealBusy} />
                </AVRBlock>
              )}

              {/* Government ID */}
              {iv.requested_fields?.includes('gov_id') && (
                <AVRBlock title="Government ID" status={iv.gov_id_completed_at ? 'done' : 'pending'}>
                  <AVRField label="Type" value={
                    iv.gov_id_type === 'drivers_license' ? "Driver's license" :
                    iv.gov_id_type === 'state_id'        ? 'State ID' :
                    iv.gov_id_type === 'passport'        ? 'US passport' : null
                  } />
                  {govUrl ? (
                    <a href={govUrl} target="_blank" rel="noopener" style={{ display:'inline-block', marginTop:8, padding:'6px 12px', background:AVR_NAVY, color:'#fff', borderRadius:8, fontSize:12, fontWeight:700, textDecoration:'none' }}>
                      Open ID photo →
                    </a>
                  ) : iv.gov_id_completed_at ? (
                    <div style={{ fontSize:12, color:AVR_MUTED, marginTop:6 }}>Generating signed URL…</div>
                  ) : null}
                </AVRBlock>
              )}

              {/* Address */}
              {iv.requested_fields?.includes('address') && (
                <AVRBlock title="Mailing address" status={iv.address_completed_at ? 'done' : 'pending'}>
                  <AVRField label="Street" value={[iv.address_line1, iv.address_line2].filter(Boolean).join(', ')} />
                  <AVRField label="City / state / ZIP" value={[iv.address_city, iv.address_state, iv.address_zip].filter(Boolean).join(', ')} />
                </AVRBlock>
              )}

              {/* Bank */}
              {iv.requested_fields?.includes('bank') && (
                <AVRBlock title="Bank for payouts" status={iv.bank_completed_at ? 'done' : 'pending'}>
                  <AVRField label="Holder name" value={iv.bank_account_holder_name} />
                  <AVRField label="Account type" value={iv.bank_account_type} />
                  <AVRRevealRow label="Routing"
                    masked={iv.bank_account_last_four ? '••• encrypted' : null}
                    revealed={decrypted?.bank_routing || null}
                    isVisible={reveal} onReveal={doReveal} busy={revealBusy} />
                  <AVRRevealRow label="Account #"
                    masked={iv.bank_account_last_four ? `••• ${iv.bank_account_last_four}` : null}
                    revealed={decrypted?.bank_account || null}
                    isVisible={reveal} onReveal={doReveal} busy={revealBusy} />
                </AVRBlock>
              )}

              {reveal && (
                <div style={{ marginBottom:14, padding:'9px 12px', background:'oklch(96% 0.05 80)', border:`1px solid ${AVR_GOLD}`, borderRadius:8, fontSize:12, color:'oklch(32% 0.1 80)', display:'flex', alignItems:'center', gap:8 }}>
                  <span>🔓</span>
                  <span>Sensitive values are visible. This access has been logged. They auto-hide in 60 seconds.</span>
                  <button onClick={() => setReveal(false)} style={{ marginLeft:'auto', background:'#fff', border:`1px solid ${AVR_GOLD}`, borderRadius:6, padding:'3px 9px', fontSize:11, fontWeight:700, color:'oklch(32% 0.1 80)', cursor:'pointer' }}>
                    Hide
                  </button>
                </div>
              )}

              {iv.rejection_reason && iv.status === 'rejected' && (
                <div style={{ background:'oklch(96% 0.04 25)', border:'1px solid oklch(88% 0.06 25)', borderRadius:10, padding:'12px 14px', fontSize:13, color:'oklch(40% 0.15 25)', marginBottom:14, lineHeight:1.55 }}>
                  <strong>Rejection reason sent to instructor:</strong> {iv.rejection_reason}
                </div>
              )}

              {error && (
                <div style={{ background:'oklch(95% 0.06 25)', color:'oklch(40% 0.15 25)', padding:'9px 12px', borderRadius:8, fontSize:12, marginBottom:12 }}>
                  {error}
                </div>
              )}

              {iv.status === 'submitted' && !rejectMode && (
                <div style={{ display:'flex', gap:10, marginTop:18 }}>
                  <button onClick={approve} disabled={busy}
                    style={{ flex:1, background:'oklch(34% 0.13 150)', color:'#fff', border:'none', borderRadius:10, padding:'12px 0', fontWeight:700, fontSize:14, cursor: busy ? 'wait' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: busy ? 0.7 : 1 }}>
                    {busy ? 'Approving…' : '✓ Approve'}
                  </button>
                  <button onClick={() => setRej(true)} disabled={busy}
                    style={{ background:'#fff', color:'oklch(40% 0.15 25)', border:'1.5px solid oklch(88% 0.06 25)', borderRadius:10, padding:'12px 20px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
                    Reject
                  </button>
                </div>
              )}

              {rejectMode && (
                <div style={{ marginTop:14, padding:'14px', background:'#fff', borderRadius:10, border:`1px solid ${AVR_BORDER}` }}>
                  <label style={{ display:'block', fontSize:12, fontWeight:700, color:AVR_INK, marginBottom:6 }}>
                    Reason (sent to instructor)
                  </label>
                  <textarea value={reason} onChange={e => setReason(e.target.value)} rows={3} placeholder="e.g., The ID photo was blurry — please retake in better lighting."
                    style={{ width:'100%', padding:'10px 12px', borderRadius:8, border:`1.5px solid ${AVR_BORDER}`, fontFamily:"'Plus Jakarta Sans', sans-serif", fontSize:13, resize:'vertical', minHeight:70, outline:'none' }} />
                  <div style={{ display:'flex', gap:10, marginTop:10 }}>
                    <button onClick={reject} disabled={busy || reason.trim().length < 4}
                      style={{ flex:1, background:'oklch(40% 0.15 25)', color:'#fff', border:'none', borderRadius:8, padding:'10px 0', fontWeight:700, fontSize:13, cursor: (busy || reason.trim().length < 4) ? 'not-allowed' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: (busy || reason.trim().length < 4) ? 0.6 : 1 }}>
                      {busy ? 'Sending…' : 'Send rejection'}
                    </button>
                    <button onClick={() => { setRej(false); setReason(''); }}
                      style={{ background:'oklch(95% 0.01 265)', border:'none', borderRadius:8, padding:'10px 18px', fontWeight:600, fontSize:13, cursor:'pointer', color:AVR_MUTED, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
                      Cancel
                    </button>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// SSN format helper for the revealed-value display (mirrors formatSSN in
// instructor-verify.jsx but defined locally so this file is independent).
const formatSSNFull = (raw) => {
  const d = String(raw || '').replace(/\D/g, '');
  if (d.length !== 9) return d;
  return d.slice(0,3) + '-' + d.slice(3,5) + '-' + d.slice(5);
};

window.AdminVerificationReview = AdminVerificationReview;
