// admin-signup-review.jsx — Modal for admins to approve/reject a tutor's
// submitted v2 signup. Mirrors the AdminVerificationReview drawer pattern
// but smaller — the v2 signup is non-sensitive (no SSN, no bank, no gov-ID),
// so this is a straight read + approve/reject. The sensitive verification
// flow remains a separate, post-approval step.

const AdminSignupReview = ({ instructor, onClose }) => {
  const isMobile = window.useIsMobile();
  const [loading, setLoading] = React.useState(true);
  const [progress, setProgress] = React.useState(null);
  const [instr, setInstr]       = React.useState(null);
  const [subjects, setSubjects] = React.useState([]);
  const [agreement, setAgreement] = React.useState(null);
  const [error, setError]   = React.useState(null);
  const [busy, setBusy]     = React.useState(false);
  const [rejecting, setRejecting] = React.useState(false);
  const [rejectReason, setRejectReason] = React.useState('');
  const [followingUp, setFollowingUp] = React.useState(false);
  const [followupSubject, setFollowupSubject] = React.useState('');
  const [followupBody,    setFollowupBody]    = React.useState('');
  const [followupSent, setFollowupSent] = React.useState(false);
  const [editingFields, setEditingFields] = React.useState(false);

  const load = React.useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const { data: prog, error: pe } = await window.supa
        .from('instructor_signup_progress').select('*').eq('instructor_id', instructor.id).maybeSingle();
      if (pe) throw pe;
      setProgress(prog);

      const { data: i, error: ie } = await window.supa
        .from('instructors').select('*').eq('id', instructor.id).maybeSingle();
      if (ie) throw ie;
      setInstr(i);

      const picked = prog?.subjects_picked || [];
      if (picked.length) {
        const { data: subs } = await window.supa.from('signup_subjects')
          .select('id, name, category_id, signup_categories(name)').in('id', picked);
        setSubjects(subs || []);
      } else {
        setSubjects([]);
      }
      if (prog?.agreement_id) {
        const { data: agr } = await window.supa.from('signup_agreements')
          .select('title, effective_from').eq('id', prog.agreement_id).maybeSingle();
        setAgreement(agr);
      }
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not load') : (e.message || String(e)));
    } finally { setLoading(false); }
  }, [instructor?.id]);

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

  const onApprove = async () => {
    if (!confirm(`Approve ${instructor.name}'s profile? They'll go live on the site.`)) return;
    setBusy(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc('admin_approve_signup', { p_instructor_id: instructor.id });
      if (e) throw e;
      onClose && onClose();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not approve') : e.message);
      setBusy(false);
    }
  };

  const onReject = async () => {
    if (!rejectReason.trim()) { setError('Please write a reason.'); return; }
    setBusy(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc('admin_reject_signup', { p_instructor_id: instructor.id, p_reason: rejectReason.trim() });
      if (e) throw e;
      onClose && onClose();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not reject') : e.message);
      setBusy(false);
    }
  };

  const onSendFollowup = async () => {
    if (!followupSubject.trim()) { setError('Subject required.'); return; }
    if (!followupBody.trim())    { setError('Body required.'); return; }
    setBusy(true); setError(null);
    try {
      // Wrap the plain-text body in the same template as the other transactional emails.
      const html =
        '<div style="font-family:system-ui,-apple-system,sans-serif;max-width:560px;margin:0 auto;padding:24px;color:#1a1d24">' +
        '<h2 style="margin:0 0 12px;font-family:Georgia,serif;font-weight:600;font-size:22px">Quick note about your tutor application</h2>' +
        '<div style="font-size:15px;line-height:1.6;margin:0 0 14px;white-space:pre-wrap">' +
        followupBody.trim().replace(/[<>]/g, c => ({ '<': '&lt;', '>': '&gt;' }[c])) +
        '</div><p style="font-size:13px;color:#5a606f;margin:24px 0 0">Coaching · hello@coachingforall.co</p></div>';
      const { error: e } = await window.supa.rpc('admin_send_followup_email', {
        p_instructor_id: instructor.id, p_subject: followupSubject.trim(), p_html: html,
      });
      if (e) throw e;
      setFollowupSent(true);
      setFollowingUp(false);
      setFollowupSubject(''); setFollowupBody('');
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not send') : e.message);
    } finally { setBusy(false); }
  };

  const status = progress?.review_status || 'in_progress';
  const pillColor =
    status === 'pending_review' ? { bg:'oklch(96% 0.07 80)',  fg:'oklch(34% 0.14 80)'  } :
    status === 'approved'       ? { bg:'oklch(94% 0.07 150)', fg:'oklch(30% 0.13 150)' } :
    status === 'rejected'       ? { bg:'oklch(95% 0.06 25)',  fg:'oklch(40% 0.15 25)'  } :
                                  { bg:'oklch(94% 0.01 265)', fg:'oklch(40% 0.04 265)' };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(15,20,35,0.55)', zIndex:200, display:'flex', justifyContent:'flex-end' }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        width: isMobile ? '100%' : 560, maxWidth:'100vw', height:'100vh',
        background:'#fff', overflowY:'auto', boxShadow:'-12px 0 36px rgba(0,0,0,0.18)',
        display:'flex', flexDirection:'column',
      }}>
        <div style={{ padding:'18px 22px', borderBottom:'1px solid oklch(94% 0.01 265)', display:'flex', justifyContent:'space-between', alignItems:'center', position:'sticky', top:0, background:'#fff', zIndex:5 }}>
          <div>
            <div style={{ fontFamily:"'Cormorant Garamond', serif", fontWeight:700, fontSize:22, color:'oklch(22% 0.06 265)' }}>Profile review</div>
            <div style={{ fontSize:13, color:'oklch(50% 0.04 265)' }}>{instructor.name}</div>
          </div>
          <button onClick={onClose} style={{ background:'none', border:'none', fontSize:24, cursor:'pointer', color:'oklch(40% 0.04 265)' }}>×</button>
        </div>

        <div style={{ padding:22, flex:1 }}>
          <div style={{ display:'inline-block', padding:'5px 12px', borderRadius:14, fontSize:12, fontWeight:700, background:pillColor.bg, color:pillColor.fg, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:18 }}>
            {status.replace('_', ' ')}
          </div>

          {loading && <div style={{ color:'oklch(50% 0.03 265)' }}>Loading…</div>}
          {!loading && (
            <>
              {instr?.photo_url && (
                <img src={instr.photo_url} alt="" style={{ width:96, height:96, borderRadius:'50%', objectFit:'cover', border:'2px solid oklch(90% 0.01 265)', marginBottom:14 }} />
              )}
              <SRBlock label="Headline" value={instr?.profile_headline || '(none)'} />
              <SRBlock label="Free response" value={instr?.free_response || instr?.bio || '(none)'} multiline />
              <SRBlock label="Subjects" value={subjects.length ? subjects.map(s => `${s.signup_categories?.name || ''} → ${s.name}`).join(' · ') : '(none)'} />
              <SRBlock label="Address" value={[
                instr?.address_line1, instr?.address_line2, instr?.address_city, instr?.address_state, instr?.address_zip
              ].filter(Boolean).join(', ') || '(none)'} />
              <SRBlock label="Phone" value={instr?.phone || '(none)'} />
              <SRBlock label="Hourly rate" value={instr?.rate ? `$${instr.rate}/hr` : '(none)'} />
              <SRBlock label="Time zone" value={instr?.time_zone || '(none)'} />
              <SRBlock label="Teaching modes" value={
                [instr?.teaches_online && 'Online', instr?.teaches_in_person && 'In person']
                  .filter(Boolean).join(' · ') || '(neither set)'
              } />
              <SRBlock label="Education" value={[
                instr?.undergrad_college && `${instr.undergrad_college}${instr.undergrad_major ? ` (${instr.undergrad_major})` : ''}`,
                instr?.grad_college_1   && `${instr.grad_college_1}${instr.grad_degree_1 ? ` (${instr.grad_degree_1})` : ''}`,
                instr?.grad_college_2   && `${instr.grad_college_2}${instr.grad_degree_2 ? ` (${instr.grad_degree_2})` : ''}`,
                instr?.teaching_certification && `Cert: ${instr.teaching_certification}`,
              ].filter(Boolean).join(' · ') || '(none)'} />
              <SRBlock label="Travel radius" value={instr?.travel_radius_miles ? `${instr.travel_radius_miles} mi` : '(none)'} />
              <SRBlock label="Agreement" value={
                progress?.signature_legal_first
                  ? `Signed by ${progress.signature_legal_first} ${progress.signature_legal_last} at ${new Date(progress.agreement_signed_at).toLocaleString()}${agreement ? ` · ${agreement.title}` : ''}`
                  : '(not signed)'
              } />
              <SRBlock label="Submitted" value={progress?.submitted_at ? new Date(progress.submitted_at).toLocaleString() : '(not yet)'} />
              {progress?.last_edited_at && progress?.submitted_at && new Date(progress.last_edited_at) > new Date(progress.submitted_at) && (
                <div style={{ background: 'oklch(96% 0.07 80)', border: '1px solid oklch(86% 0.1 80)', color: 'oklch(34% 0.14 80)',
                  padding: '8px 12px', borderRadius: 8, fontSize: 13, marginBottom: 14, fontWeight: 600 }}>
                  Edited by tutor after submission · last change {new Date(progress.last_edited_at).toLocaleString()}
                </div>
              )}
              {status === 'rejected' && (
                <SRBlock label="Rejection reason" value={progress?.rejection_reason || '(none)'} multiline />
              )}
              {followupSent && (
                <div style={{ background: 'oklch(95% 0.07 155)', border: '1px solid oklch(80% 0.13 155)',
                  color: 'oklch(32% 0.13 155)', padding: '8px 12px', borderRadius: 8, fontSize: 13, marginTop: 6 }}>
                  Follow-up email sent.
                </div>
              )}
            </>
          )}

          {error && <div style={{ background:'oklch(96% 0.03 25)', color:'oklch(40% 0.15 25)', padding:'10px 14px', borderRadius:8, fontSize:13, marginTop:14, border:'1px solid oklch(88% 0.06 25)' }}>{error}</div>}
        </div>

        {!loading && (status === 'draft' || status === 'pending_review' || status === 'rejected') && (
          <div style={{ borderTop:'1px solid oklch(94% 0.01 265)', padding:'16px 22px', background:'oklch(99% 0.005 265)', position:'sticky', bottom:0 }}>
            {followingUp ? (
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:'oklch(28% 0.05 265)', marginBottom:8 }}>Send the tutor a follow-up email</div>
                <input value={followupSubject} onChange={e=>setFollowupSubject(e.target.value)} placeholder="Subject"
                  style={{ width:'100%', padding:'10px 12px', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:8,
                    fontSize:14, fontFamily:"'Plus Jakarta Sans', sans-serif", outline:'none', marginBottom:8 }} />
                <textarea value={followupBody} onChange={e=>setFollowupBody(e.target.value)} rows={4}
                  placeholder="Body (plain text — line breaks preserved)"
                  style={{ width:'100%', padding:'10px 12px', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:8,
                    fontSize:14, fontFamily:"'Plus Jakarta Sans', sans-serif", outline:'none', resize:'vertical' }} />
                <div style={{ display:'flex', gap:8, justifyContent:'flex-end', marginTop:10 }}>
                  <button onClick={() => { setFollowingUp(false); setFollowupSubject(''); setFollowupBody(''); }} disabled={busy} style={{
                    background:'#fff', color:'oklch(28% 0.05 265)', border:'1.5px solid oklch(85% 0.02 265)',
                    borderRadius:8, padding:'9px 18px', fontWeight:600, fontSize:13, cursor:'pointer',
                  }}>Cancel</button>
                  <button onClick={onSendFollowup} disabled={busy || !followupSubject.trim() || !followupBody.trim()} style={{
                    background:'oklch(35% 0.12 265)', color:'#fff', border:'none', borderRadius:8,
                    padding:'9px 22px', fontWeight:700, fontSize:13, cursor: busy ? 'wait' : 'pointer',
                    opacity: (followupSubject.trim() && followupBody.trim()) ? 1 : 0.5,
                  }}>{busy ? 'Sending…' : 'Send email'}</button>
                </div>
              </div>
            ) : !rejecting ? (
              <div style={{ display:'flex', gap:10, justifyContent:'flex-end', flexWrap:'wrap' }}>
                <button onClick={() => setEditingFields(true)} disabled={busy} style={{
                  background:'#fff', color:'oklch(35% 0.12 265)', border:'1.5px solid oklch(80% 0.05 265)',
                  borderRadius:8, padding:'11px 18px', fontWeight:600, fontSize:13.5, cursor: busy ? 'wait' : 'pointer',
                }}>Edit fields</button>
                <button onClick={() => setFollowingUp(true)} disabled={busy} style={{
                  background:'#fff', color:'oklch(35% 0.12 265)', border:'1.5px solid oklch(80% 0.05 265)',
                  borderRadius:8, padding:'11px 18px', fontWeight:600, fontSize:13.5, cursor: busy ? 'wait' : 'pointer',
                }}>Send follow-up email</button>
                {status === 'pending_review' && <>
                  <button onClick={() => setRejecting(true)} disabled={busy} style={{
                    background:'#fff', color:'oklch(40% 0.15 25)', border:'1.5px solid oklch(85% 0.07 25)',
                    borderRadius:8, padding:'11px 22px', fontWeight:700, fontSize:14, cursor: busy ? 'wait' : 'pointer',
                  }}>Reject</button>
                  <button onClick={onApprove} disabled={busy} style={{
                    background:'oklch(34% 0.13 150)', color:'#fff', border:'none', borderRadius:8,
                    padding:'11px 26px', fontWeight:700, fontSize:14, cursor: busy ? 'wait' : 'pointer',
                  }}>{busy ? 'Approving…' : '✓ Approve'}</button>
                </>}
              </div>
            ) : (
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:'oklch(28% 0.05 265)', marginBottom:8 }}>Reason for rejection (the tutor will see this)</div>
                <textarea value={rejectReason} onChange={e=>setRejectReason(e.target.value)} rows={3} style={{
                  width:'100%', padding:'10px 12px', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:8,
                  fontSize:14, fontFamily:"'Plus Jakarta Sans', sans-serif", outline:'none', resize:'vertical',
                }} placeholder="e.g. Please add more detail to your bio — at least 2 paragraphs about your teaching experience." />
                <div style={{ display:'flex', gap:8, justifyContent:'flex-end', marginTop:10 }}>
                  <button onClick={() => { setRejecting(false); setRejectReason(''); }} disabled={busy} style={{
                    background:'#fff', color:'oklch(28% 0.05 265)', border:'1.5px solid oklch(85% 0.02 265)',
                    borderRadius:8, padding:'9px 18px', fontWeight:600, fontSize:13, cursor:'pointer',
                  }}>Cancel</button>
                  <button onClick={onReject} disabled={busy || !rejectReason.trim()} style={{
                    background:'oklch(50% 0.18 25)', color:'#fff', border:'none', borderRadius:8,
                    padding:'9px 22px', fontWeight:700, fontSize:13, cursor: busy ? 'wait' : 'pointer',
                    opacity: rejectReason.trim() ? 1 : 0.5,
                  }}>{busy ? 'Rejecting…' : 'Confirm rejection'}</button>
                </div>
              </div>
            )}
          </div>
        )}

        {editingFields && window.AdminOnboardingEdit && (
          <window.AdminOnboardingEdit
            instructor={instructor}
            onClose={() => setEditingFields(false)}
            onSaved={() => load()}
          />
        )}
      </div>
    </div>
  );
};

const SRBlock = ({ label, value, multiline }) => (
  <div style={{ marginBottom:14 }}>
    <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', marginBottom:3 }}>{label}</div>
    <div style={{ fontSize:14, color:'oklch(22% 0.04 265)', lineHeight:1.55, whiteSpace: multiline ? 'pre-wrap' : 'normal' }}>{value}</div>
  </div>
);

window.AdminSignupReview = AdminSignupReview;
