// admin-onboarding-edit.jsx — Drawer that lets the admin edit every
// onboarding field a teacher fills in (basic info, profile, modality).
// Backed by admin_save_onboarding RPC (v70). Opens from the signup-review
// modal via the "Edit fields" toggle.

const AOE_INK   = 'oklch(22% 0.06 265)';
const AOE_MUTED = 'oklch(50% 0.03 265)';

const AOEField = ({ label, children, span }) => (
  <div style={{ marginBottom: 14, gridColumn: span ? `span ${span}` : 'auto' }}>
    <label style={{ display:'block', fontSize:12.5, fontWeight:600, color:'oklch(35% 0.04 265)', marginBottom:6 }}>{label}</label>
    {children}
  </div>
);
const aoeInput = {
  width:'100%', padding:'9px 12px', border:'1.5px solid oklch(88% 0.01 265)',
  borderRadius:8, fontSize:14, fontFamily:"'Plus Jakarta Sans', sans-serif", outline:'none',
};

const AdminOnboardingEdit = ({ instructor, onClose, onSaved }) => {
  const isMobile = window.useIsMobile();
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving]   = React.useState(false);
  const [error, setError]     = React.useState(null);
  const [savedFlash, setSavedFlash] = React.useState(false);
  const [row, setRow] = React.useState({});

  const load = React.useCallback(async () => {
    setLoading(true); setError(null);
    try {
      const { data, error: e } = await window.supa.from('instructors').select('*').eq('id', instructor.id).maybeSingle();
      if (e) throw e;
      setRow({
        full_name: data?.full_name || '',
        profile_headline: data?.profile_headline || '',
        free_response:    data?.free_response || data?.bio || '',
        photo_url:        data?.photo_url || '',
        gender:           data?.gender || '',
        time_zone:        data?.time_zone || '',
        cancellation_notice: data?.cancellation_notice || '',
        rate:             data?.rate ?? '',
        address_line1:    data?.address_line1 || '',
        address_line2:    data?.address_line2 || '',
        address_city:     data?.address_city || data?.city || '',
        address_state:    data?.address_state || data?.state || '',
        address_zip:      data?.address_zip || '',
        phone:            data?.phone || '',
        undergrad_college: data?.undergrad_college || '',
        undergrad_major:   data?.undergrad_major || '',
        grad_college_1:    data?.grad_college_1 || '',
        grad_degree_1:     data?.grad_degree_1 || '',
        grad_college_2:    data?.grad_college_2 || '',
        grad_degree_2:     data?.grad_degree_2 || '',
        teaching_certification: data?.teaching_certification || '',
        privacy_radius_miles:   data?.privacy_radius_miles ?? '',
        travel_radius_miles:    data?.travel_radius_miles ?? '',
        teaches_online:    data?.teaches_online    !== false,
        teaches_in_person: data?.teaches_in_person === true,
      });
    } 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 set = (k, v) => setRow(r => ({ ...r, [k]: v }));

  const onSave = async () => {
    setSaving(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc('admin_save_onboarding', {
        p_instructor_id: instructor.id,
        p: row,
      });
      if (e) throw e;
      setSavedFlash(true);
      setTimeout(() => setSavedFlash(false), 2500);
      if (onSaved) await onSaved();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not save') : e.message);
    } finally { setSaving(false); }
  };

  const onUploadPhoto = async (file) => {
    if (!file) return;
    if (file.size > 8 * 1024 * 1024) { setError('Photo must be ≤ 8 MB.'); return; }
    setSaving(true); setError(null);
    try {
      const ext = (file.name.split('.').pop() || 'jpg').toLowerCase();
      const objPath = `${instructor.id}/admin-${Date.now()}.${ext}`;
      const { error: e } = await window.supa.storage.from('instructor-photos')
        .upload(objPath, file, { upsert: true, contentType: file.type });
      if (e) throw e;
      const { data: pub } = window.supa.storage.from('instructor-photos').getPublicUrl(objPath);
      set('photo_url', pub.publicUrl);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Upload failed') : e.message);
    } finally { setSaving(false); }
  };

  if (loading) return (
    <div style={{ position:'fixed', inset:0, background:'rgba(15,20,35,0.55)', zIndex:300, display:'flex', justifyContent:'flex-end' }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{ width: isMobile ? '100%' : 640, height:'100vh', background:'#fff', padding:24, color:AOE_MUTED }}>
        Loading…
      </div>
    </div>
  );

  const twoCol = isMobile ? '1fr' : '1fr 1fr';

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(15,20,35,0.55)', zIndex:300, display:'flex', justifyContent:'flex-end' }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        width: isMobile ? '100%' : 640, 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:AOE_INK }}>Edit onboarding fields</div>
            <div style={{ fontSize:13, color:AOE_MUTED }}>{instructor.name || row.full_name}</div>
          </div>
          <button onClick={onClose} style={{ background:'none', border:'none', fontSize:24, cursor:'pointer', color:AOE_MUTED }}>×</button>
        </div>

        <div style={{ padding:22, flex:1 }}>
          {error && <div style={{ background:'oklch(96% 0.03 25)', color:'oklch(40% 0.15 25)', padding:'10px 14px', borderRadius:8, fontSize:13, marginBottom:14, border:'1px solid oklch(88% 0.06 25)' }}>{error}</div>}
          {savedFlash && <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, marginBottom:14 }}>Saved.</div>}

          <h3 style={{ fontSize:13, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', margin:'4px 0 12px' }}>Identity</h3>
          <div style={{ display:'grid', gridTemplateColumns: twoCol, gap:14 }}>
            <AOEField label="Full name" span={2}><input value={row.full_name} onChange={e=>set('full_name', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Profile headline" span={2}><input value={row.profile_headline} onChange={e=>set('profile_headline', e.target.value)} maxLength={140} style={aoeInput} /></AOEField>
            <AOEField label="Free response / bio" span={2}>
              <textarea value={row.free_response} onChange={e=>set('free_response', e.target.value)} rows={5} style={{ ...aoeInput, resize:'vertical', lineHeight:1.55 }} />
            </AOEField>
            <AOEField label="Profile photo" span={2}>
              <div style={{ display:'flex', alignItems:'center', gap:12, flexWrap:'wrap' }}>
                {row.photo_url && <img src={row.photo_url} alt="" style={{ width:60, height:60, borderRadius:'50%', objectFit:'cover', border:'2px solid oklch(90% 0.01 265)' }} />}
                <label style={{ padding:'8px 14px', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:8, cursor:'pointer', fontSize:13, fontWeight:600 }}>
                  Upload new
                  <input type="file" accept="image/*" onChange={e=>onUploadPhoto(e.target.files?.[0])} style={{ display:'none' }} />
                </label>
                {row.photo_url && (
                  <button onClick={()=>set('photo_url','')} style={{ background:'none', border:'1px solid oklch(85% 0.02 265)', padding:'6px 12px', borderRadius:6, fontSize:12, cursor:'pointer', color:'oklch(40% 0.04 265)' }}>Clear</button>
                )}
              </div>
            </AOEField>
          </div>

          <h3 style={{ fontSize:13, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', margin:'18px 0 12px' }}>Rate & modality</h3>
          <div style={{ display:'grid', gridTemplateColumns: twoCol, gap:14 }}>
            <AOEField label="Hourly rate (USD)">
              <input type="number" min={0} max={500} value={row.rate} onChange={e=>set('rate', e.target.value)} style={aoeInput} />
            </AOEField>
            <AOEField label="Cancellation notice">
              <select value={row.cancellation_notice} onChange={e=>set('cancellation_notice', e.target.value)} style={aoeInput}>
                <option value="">None</option>
                <option value="2h">2 hours</option>
                <option value="6h">6 hours</option>
                <option value="12h">12 hours</option>
                <option value="24h">24 hours</option>
              </select>
            </AOEField>
            <AOEField label="Teaches online" span={1}>
              <label style={{ display:'flex', alignItems:'center', gap:8, padding:'6px 0' }}>
                <input type="checkbox" checked={row.teaches_online} onChange={e=>set('teaches_online', e.target.checked)} style={{ width:18, height:18 }} />
                <span style={{ fontSize:13 }}>Yes</span>
              </label>
            </AOEField>
            <AOEField label="Teaches in person" span={1}>
              <label style={{ display:'flex', alignItems:'center', gap:8, padding:'6px 0' }}>
                <input type="checkbox" checked={row.teaches_in_person} onChange={e=>set('teaches_in_person', e.target.checked)} style={{ width:18, height:18 }} />
                <span style={{ fontSize:13 }}>Yes</span>
              </label>
            </AOEField>
          </div>

          <h3 style={{ fontSize:13, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', margin:'18px 0 12px' }}>Address</h3>
          <div style={{ display:'grid', gridTemplateColumns: twoCol, gap:14 }}>
            <AOEField label="Address line 1" span={2}><input value={row.address_line1} onChange={e=>set('address_line1', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Address line 2" span={2}><input value={row.address_line2} onChange={e=>set('address_line2', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="City"><input value={row.address_city} onChange={e=>set('address_city', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="State (2-letter)"><input value={row.address_state} maxLength={2} onChange={e=>set('address_state', e.target.value.toUpperCase().slice(0,2))} style={aoeInput} /></AOEField>
            <AOEField label="ZIP"><input value={row.address_zip} onChange={e=>set('address_zip', e.target.value.replace(/\D/g,'').slice(0,5))} style={aoeInput} /></AOEField>
            <AOEField label="Phone"><input type="tel" value={row.phone} onChange={e=>set('phone', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Privacy radius (mi)"><input type="number" step="0.01" value={row.privacy_radius_miles} onChange={e=>set('privacy_radius_miles', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Travel radius (mi)"><input type="number" value={row.travel_radius_miles} onChange={e=>set('travel_radius_miles', e.target.value)} style={aoeInput} /></AOEField>
          </div>

          <h3 style={{ fontSize:13, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', margin:'18px 0 12px' }}>Identity & TZ</h3>
          <div style={{ display:'grid', gridTemplateColumns: twoCol, gap:14 }}>
            <AOEField label="Gender">
              <select value={row.gender} onChange={e=>set('gender', e.target.value)} style={aoeInput}>
                <option value="">—</option><option>Male</option><option>Female</option>
                <option>Non-binary</option><option>Prefer not to say</option>
              </select>
            </AOEField>
            <AOEField label="Time zone">
              <select value={row.time_zone} onChange={e=>set('time_zone', e.target.value)} style={aoeInput}>
                <option value="">—</option>
                <option value="America/New_York">New York (Eastern)</option>
                <option value="America/Chicago">Chicago (Central)</option>
                <option value="America/Denver">Denver (Mountain)</option>
                <option value="America/Los_Angeles">Los Angeles (Pacific)</option>
                <option value="America/Phoenix">Phoenix</option>
                <option value="America/Anchorage">Anchorage</option>
                <option value="Pacific/Honolulu">Honolulu</option>
              </select>
            </AOEField>
          </div>

          <h3 style={{ fontSize:13, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', margin:'18px 0 12px' }}>Education</h3>
          <div style={{ display:'grid', gridTemplateColumns: twoCol, gap:14 }}>
            <AOEField label="Undergrad college"><input value={row.undergrad_college} onChange={e=>set('undergrad_college', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Undergrad major"><input value={row.undergrad_major} onChange={e=>set('undergrad_major', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Grad college 1"><input value={row.grad_college_1} onChange={e=>set('grad_college_1', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Grad degree 1">
              <select value={row.grad_degree_1} onChange={e=>set('grad_degree_1', e.target.value)} style={aoeInput}>
                <option value="">—</option><option>Master's</option><option>Doctorate</option><option>Professional</option><option>Certificate</option>
              </select>
            </AOEField>
            <AOEField label="Grad college 2"><input value={row.grad_college_2} onChange={e=>set('grad_college_2', e.target.value)} style={aoeInput} /></AOEField>
            <AOEField label="Grad degree 2">
              <select value={row.grad_degree_2} onChange={e=>set('grad_degree_2', e.target.value)} style={aoeInput}>
                <option value="">—</option><option>Master's</option><option>Doctorate</option><option>Professional</option><option>Certificate</option>
              </select>
            </AOEField>
            <AOEField label="Teaching certification" span={2}>
              <select value={row.teaching_certification} onChange={e=>set('teaching_certification', e.target.value)} style={aoeInput}>
                <option value="">Not certified</option><option>State Certified</option><option>National Board Certified</option><option>Other</option>
              </select>
            </AOEField>
          </div>
        </div>

        <div style={{ borderTop:'1px solid oklch(94% 0.01 265)', padding:'14px 22px', background:'oklch(99% 0.005 265)', position:'sticky', bottom:0, display:'flex', justifyContent:'space-between', alignItems:'center', gap:12 }}>
          <div style={{ fontSize:12, color:AOE_MUTED }}>Admin edits are audited.</div>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={onClose} disabled={saving} style={{
              background:'#fff', color:AOE_INK, border:'1.5px solid oklch(85% 0.02 265)',
              borderRadius:8, padding:'10px 18px', fontWeight:600, fontSize:13, cursor:'pointer',
            }}>Close</button>
            <button onClick={onSave} disabled={saving} style={{
              background:'oklch(35% 0.12 265)', color:'#fff', border:'none', borderRadius:8,
              padding:'10px 22px', fontWeight:700, fontSize:13.5, cursor: saving ? 'wait' : 'pointer',
            }}>{saving ? 'Saving…' : 'Save changes'}</button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.AdminOnboardingEdit = AdminOnboardingEdit;
