// src/features/admin/ui/admin-instructors-modals-edit.jsx
//
// The "Edit instructor (everything)" modal — name, subject, rate,
// bio, badges, money-adjustments. Split off from
// admin-instructors-modals.jsx so the parent stays under the 400 LOC
// budget.
//
// Public: window.AIEditInstructorModal (+ legacy alias
// AdminEditInstructorModal for admin-view-as.jsx).
//
// Reads from window: AddressAutosuggest (published by
// admin-instructors-modals.jsx, which loads first).

const { AddressAutosuggest } = window;

// ── Edit Instructor (everything: name, subject, rate, bio, badges, money adjustments) ──
const AIEditInstructorModal = ({ instructor, onClose }) => {
  const data = window.useAdminData();
  const [form, setForm] = React.useState({
    name: instructor.name || '',
    topics: instructor.topics && instructor.topics.length ? instructor.topics : (instructor.subject ? [instructor.subject] : ['Piano']),
    category: instructor.category || 'music',
    rate: instructor.rate || 0,
    experience: instructor.experience || 0,
    bio: instructor.bio || '',
    specialties: (instructor.specialties || []).join(', '),
    badges: (instructor.badges || []).join(', '),
    available: instructor.available !== false,
    earnedAdjustment: instructor.earnedAdjustment || 0,
    cashAdjustment:   instructor.cashAdjustment   || 0,
    payoutAdjustment: instructor.payoutAdjustment || 0,
    hue: instructor.hue || 220,
  });
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const set = (k,v) => setForm(f => ({...f, [k]:v}));

  // v134: a teacher has ONE pay rate across all students. It lives in the
  // admin-only instructor_pay_rates table (kept off the public instructors
  // row so students can't see our margin). Fetch on open, save on submit
  // (only when changed). The DB triggers cascade a change to the teacher's
  // assignments + all their UNSETTLED bookings.
  const [payRate, setPayRate] = React.useState('');
  const [origPayRate, setOrigPayRate] = React.useState(null);
  React.useEffect(() => {
    let alive = true;
    data.fetchTeacherPayRate(instructor.id)
      .then(v => { if (alive) { setPayRate(v == null ? '' : String(v)); setOrigPayRate(v); } })
      .catch(() => {});
    return () => { alive = false; };
  }, [instructor.id]);

  const fld = { width:'100%', padding:'12px 14px', borderRadius:8, border:'1.5px solid oklch(88% 0.015 265)', fontSize:16, minHeight:44, fontFamily:"'Plus Jakarta Sans', sans-serif", color:'oklch(22% 0.06 265)', background:'#fff', outline:'none', boxSizing:'border-box' };
  const lbl = { display:'block', fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(52% 0.04 265)', marginBottom:5 };
  const hint = { fontSize:10, color:'oklch(60% 0.03 265)', marginTop:4, lineHeight:1.4 };

  const SUBJECTS = ['Piano','Guitar','Violin','Vocals','Drums','Bass','Saxophone','Cello','Flute','Ukulele','Trumpet',
    'Drawing','Painting','Photography','Watercolor','Ballet','Contemporary Dance','Hip Hop','Salsa','Ballroom',
    'Golf','Tennis','Basketball','Swimming','Soccer','Yoga','Fitness Training','Martial Arts','Boxing',
    'Acting','Improv','Musical Theater'];
  const CATEGORIES = ['music','arts','dance','sports','theater'];

  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    setBusy(true); setError('');
    if (!form.topics || form.topics.length === 0) { setError('Pick at least one topic.'); setBusy(false); return; }
    try {
      await data.updateInstructor(instructor.id, {
        name: form.name.trim(),
        topics: form.topics,
        subject: form.topics[0],
        category: form.category,
        rate: form.rate,
        experience: form.experience,
        bio: form.bio,
        specialties: form.specialties.split(',').map(s=>s.trim()).filter(Boolean),
        badges:      form.badges.split(',').map(s=>s.trim()).filter(Boolean),
        available: form.available,
        hue: form.hue,
        earnedAdjustment: form.earnedAdjustment,
        cashAdjustment:   form.cashAdjustment,
        payoutAdjustment: form.payoutAdjustment,
      });
      // Save the single pay rate only when it actually changed (avoids
      // firing the propagate trigger on an unrelated edit).
      if (payRate !== '' && Number(payRate) !== Number(origPayRate)) {
        await data.setTeacherPayRate(instructor.id, Number(payRate));
      }
      onClose();
    } catch (err) {
      setError(err.message || 'Could not save changes.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.4)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9000 }} onClick={onClose}>
      <div style={{ background:'#fff', borderRadius:16, padding:'26px', width:540, maxHeight:'92vh', overflowY:'auto', boxShadow:'0 20px 60px rgba(0,0,0,0.2)', fontFamily:"'Plus Jakarta Sans', sans-serif" }} onClick={e=>e.stopPropagation()}>
        <div style={{ fontWeight:700, fontSize:16, color:'oklch(18% 0.03 265)', marginBottom:4 }}>Edit instructor</div>
        <div style={{ fontSize:12, color:'oklch(58% 0.03 265)', marginBottom:18 }}>Studio + availability are edited from the buttons on the card.</div>
        <form onSubmit={submit}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:14 }}>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Full name</label>
              <input value={form.name} onChange={e=>set('name', e.target.value)} required style={fld} />
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Topics taught <span style={{ fontWeight:500, color:'oklch(60% 0.03 265)', textTransform:'none', letterSpacing:0 }}>· tap to add/remove (first is the primary)</span></label>
              <div style={{ display:'flex', flexWrap:'wrap', gap:6, padding:'10px', border:'1.5px solid oklch(88% 0.015 265)', borderRadius:8, background:'oklch(99% 0.003 60)', maxHeight:160, overflowY:'auto' }}>
                {SUBJECTS.map(s => {
                  const on = form.topics.includes(s);
                  return (
                    <button key={s} type="button"
                      onClick={() => set('topics', on ? form.topics.filter(x=>x!==s) : [...form.topics, s])}
                      style={{ padding:'5px 11px', borderRadius:14, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif",
                        background: on ? 'oklch(22% 0.06 265)' : '#fff',
                        color: on ? '#fff' : 'oklch(40% 0.04 265)',
                        border: on ? '1.5px solid oklch(22% 0.06 265)' : '1.5px solid oklch(88% 0.02 265)' }}>
                      {on ? '✓ ' : ''}{s}
                    </button>
                  );
                })}
              </div>
            </div>
            <div>
              <label style={lbl}>Category</label>
              <select value={form.category} onChange={e=>set('category', e.target.value)} style={fld}>
                {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label style={lbl}>Experience (yrs)</label>
              <input type="number" value={form.experience} onChange={e=>set('experience', e.target.value)} min={0} max={80} style={fld} />
            </div>
            <div>
              <label style={lbl}>Marketplace price ($/hr)</label>
              <input type="number" value={form.rate} onChange={e=>set('rate', e.target.value)} min={0} max={500} style={fld} />
              <div style={hint}>What students see on the listing.</div>
            </div>
            <div>
              <label style={lbl}>Teacher pay rate ($/hr)</label>
              <input type="number" value={payRate} onChange={e=>setPayRate(e.target.value)} min={0} max={1000} step="0.01" placeholder="— not set —" style={fld} />
              <div style={hint}>What you pay them — applies to every student. Updating it re-prices all their unpaid lessons.</div>
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Bio</label>
              <textarea value={form.bio} onChange={e=>set('bio', e.target.value)} rows={3} style={{...fld, resize:'vertical', fontFamily:"'Plus Jakarta Sans', sans-serif"}} placeholder="Short profile blurb shown to students" />
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Specialties (comma-separated)</label>
              <input value={form.specialties} onChange={e=>set('specialties', e.target.value)} placeholder="Classical, Jazz, Beginners" style={fld} />
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Badges (comma-separated)</label>
              <input value={form.badges} onChange={e=>set('badges', e.target.value)} placeholder="Top Rated, Verified Pro" style={fld} />
            </div>
            <div>
              <label style={lbl}>Status</label>
              <select value={form.available ? 'open' : 'wait'} onChange={e=>set('available', e.target.value === 'open')} style={fld}>
                <option value="open">Available — bookable</option>
                <option value="wait">Waitlist — hidden from booking</option>
              </select>
            </div>
            <div>
              <label style={lbl}>Avatar hue (0–360)</label>
              <input type="number" value={form.hue} onChange={e=>set('hue', e.target.value)} min={0} max={360} style={fld} />
            </div>
          </div>

          <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(52% 0.04 265)', marginBottom:6, paddingTop:14, borderTop:'1px solid oklch(92% 0.01 265)' }}>Manual money adjustments</div>
          <div style={{ fontSize:11, color:'oklch(60% 0.03 265)', marginBottom:12, lineHeight:1.5 }}>Added on top of the auto-computed totals (which come from bookings). Use negative numbers to subtract. Use this for off-platform lessons or one-off corrections.</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12, marginBottom:18 }}>
            <div>
              <label style={lbl}>Earned ± ($)</label>
              <input type="number" step="0.01" value={form.earnedAdjustment} onChange={e=>set('earnedAdjustment', e.target.value)} style={fld} />
            </div>
            <div>
              <label style={lbl}>Cash to send ± ($)</label>
              <input type="number" step="0.01" value={form.cashAdjustment} onChange={e=>set('cashAdjustment', e.target.value)} style={fld} />
            </div>
            <div>
              <label style={lbl}>Payout due ± ($)</label>
              <input type="number" step="0.01" value={form.payoutAdjustment} onChange={e=>set('payoutAdjustment', e.target.value)} style={fld} />
            </div>
          </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>}

          <div style={{ display:'flex', gap:10 }}>
            <button type="submit" disabled={busy} style={{ flex:1, background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:9, padding:'12px 0', fontWeight:600, fontSize:14, cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity:busy?0.7:1 }}>
              {busy ? 'Saving…' : 'Save changes'}
            </button>
            <button type="button" onClick={onClose} style={{ padding:'12px 18px', background:'oklch(95% 0.01 265)', border:'none', borderRadius:9, fontSize:14, cursor:'pointer', color:'oklch(45% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Cancel</button>
          </div>
        </form>
      </div>
    </div>
  );
};

Object.assign(window, {
  AIEditInstructorModal,
  AdminEditInstructorModal: AIEditInstructorModal,
});
