// src/features/admin/ui/admin-instructors-modals-2.jsx
//
// Second slice of the AdminInstructors modals: actions that ADD to an
// instructor record (creating a brand new student, assigning an
// existing student). The book-lesson + confirm-delete modals were
// extracted into admin-instructors-modals-3.jsx so both halves stay
// under the 400 LOC budget.
//
// Public on window: AIAddStudentModal, AIAssignStudentModal.

const AIAddStudentModal = ({ onClose }) => {
  const data = window.useAdminData();
  const defaultAvail = Object.fromEntries([0,1,2,3,4,5,6].map(i => [i, { enabled:false, blocks:[{from:9,to:17}] }]));
  const [form, setForm] = React.useState({
    name:'', phone:'', email:'', address:'', topic:'', notes:'',
    availability: defaultAvail, availabilityNote:'',
  });
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [created, setCreated] = React.useState(null);
  const set = (k,v) => setForm(f => ({...f, [k]:v}));

  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 STD_SUBJECTS = ['Piano','Guitar','Violin','Vocals','Drums','Bass','Saxophone','Cello','Flute','Ukulele','Trumpet','Drawing','Painting','Photography','Ballet','Hip Hop','Yoga','Tennis','Boxing','Acting','— Other —'];

  const toggleDay = (di) => {
    setForm(f => {
      const cur = f.availability[di] || { enabled:false, blocks:[{from:9,to:17}] };
      return { ...f, availability: { ...f.availability, [di]: { ...cur, enabled: !cur.enabled } } };
    });
  };
  const setBlock = (di, bi, key, val) => {
    setForm(f => {
      const cur = f.availability[di] || { enabled:false, blocks:[{from:9,to:17}] };
      const blocks = cur.blocks.map((b, i) => i === bi ? { ...b, [key]: Number(val) } : b);
      return { ...f, availability: { ...f.availability, [di]: { ...cur, blocks } } };
    });
  };
  const addBlock = (di) => {
    setForm(f => {
      const cur = f.availability[di] || { enabled:true, blocks:[] };
      return { ...f, availability: { ...f.availability, [di]: { ...cur, enabled:true, blocks:[...cur.blocks, {from:18, to:20}] } } };
    });
  };

  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;
    if (!form.name.trim() || !form.email.trim()) { setError('Name and email are required.'); return; }
    setBusy(true); setError('');
    try {
      const res = await data.createStudent({
        name: form.name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        address: form.address.trim(),
        topic: form.topic && form.topic !== '— Other —' ? form.topic : '',
        notes: form.notes.trim(),
        availability: form.availability,
        availabilityNote: form.availabilityNote.trim(),
      });
      setCreated({ name: form.name.trim(), email: res.email, id: res.id });
    } catch (err) {
      setError(err.message || 'Could not add student.');
    } finally {
      setBusy(false);
    }
  };

  if (created) return <MagicLinkPostCreate name={created.name} email={created.email} studentId={created.id} onClose={onClose} />;

  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:560, 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 }}>Add student</div>
        <div style={{ fontSize:12, color:'oklch(58% 0.03 265)', marginBottom:18 }}>Email is the login (magic link). Everything else is optional.</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)} placeholder="Alex Johnson" required style={fld} />
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Email * (login)</label>
              <input type="email" value={form.email} onChange={e=>set('email', e.target.value)} placeholder="alex@example.com" required style={fld} />
              <div style={{ fontSize:11, color:'oklch(58% 0.03 265)', marginTop:4 }}>They log in via a magic-link sent to this email — no password needed.</div>
            </div>
            <div>
              <label style={lbl}>Phone (contact)</label>
              <input type="tel" value={form.phone} onChange={e=>set('phone', e.target.value)} placeholder="(212) 555-0123" style={fld} />
            </div>
            <div>
              <label style={lbl}>Topic</label>
              <select value={form.topic} onChange={e=>set('topic', e.target.value)} style={fld}>
                <option value="">— None —</option>
                {STD_SUBJECTS.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Address (optional)</label>
              <input value={form.address} onChange={e=>set('address', e.target.value)} placeholder="245 W 72nd St, New York, NY" style={fld} />
            </div>
            <div style={{ gridColumn:'1/-1' }}>
              <label style={lbl}>Notes (admin-only)</label>
              <textarea value={form.notes} onChange={e=>set('notes', e.target.value)} rows={2} placeholder="Any context — referral, scheduling preference, etc." style={{...fld, resize:'vertical', fontFamily:"'Plus Jakarta Sans', sans-serif"}} />
            </div>
          </div>

          <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.07em', color:'oklch(52% 0.04 265)', marginBottom:8, paddingTop:12, borderTop:'1px solid oklch(92% 0.01 265)' }}>Availability (optional)</div>
          <div style={{ marginBottom:14 }}>
            {AI_DAYS.map((dn, di) => {
              const day = form.availability[di] || { enabled:false, blocks:[{from:9,to:17}] };
              return (
                <div key={di} style={{ display:'flex', alignItems:'center', gap:10, marginBottom:6, fontSize:12 }}>
                  <button type="button" onClick={()=>toggleDay(di)} style={{ width:50, padding:'6px 0', borderRadius:6, border:'none', cursor:'pointer', background: day.enabled ? 'oklch(44% 0.12 150)' : 'oklch(94% 0.01 265)', color: day.enabled ? '#fff' : 'oklch(60% 0.03 265)', fontWeight:700, fontSize:11 }}>
                    {dn}
                  </button>
                  {day.enabled ? (
                    <>
                      {day.blocks.map((b, bi) => (
                        <span key={bi} style={{ display:'inline-flex', alignItems:'center', gap:4, fontSize:11, color:'oklch(40% 0.04 265)' }}>
                          <input type="number" min={0} max={23} value={b.from} onChange={e=>setBlock(di, bi, 'from', e.target.value)} style={{ width:46, padding:'4px 6px', borderRadius:5, border:'1px solid oklch(88% 0.02 265)', fontSize:11 }} />
                          –
                          <input type="number" min={1} max={24} value={b.to}   onChange={e=>setBlock(di, bi, 'to',   e.target.value)} style={{ width:46, padding:'4px 6px', borderRadius:5, border:'1px solid oklch(88% 0.02 265)', fontSize:11 }} />
                        </span>
                      ))}
                      <button type="button" onClick={()=>addBlock(di)} style={{ background:'none', border:'1px dashed oklch(80% 0.02 265)', borderRadius:5, padding:'4px 8px', fontSize:11, cursor:'pointer', color:'oklch(50% 0.04 265)' }}>+ block</button>
                    </>
                  ) : (
                    <span style={{ fontSize:11, color:'oklch(70% 0.02 265)' }}>off</span>
                  )}
                </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 ? 'Creating…' : 'Add student'}
            </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>
  );
};

// ── Assign Student Modal ─────────────────────────────────────────────────────
// Pairs an existing student with this instructor + sets the rate Joe agreed.
// We let the admin enter ONE student-side hourly + ONE teacher-side hourly,
// then we auto-derive the 30/45/60/90 min rates by pro-rating.
const AIAssignStudentModal = ({ instructor, onClose }) => {
  const data = window.useAdminData();
  const [studentId, setStudentId] = React.useState('');
  // Empty defaults — fields populate ONCE a student is picked. Teacher rate
  // pre-fills from the instructor's listed $/hr (admin can override).
  const [studentHourly, setStudentHourly] = React.useState('');
  const [teacherHourly, setTeacherHourly] = React.useState(instructor.rate || '');
  // OFF by default (v134, Joe 2026-06-01): assignment confirmation emails are
  // now opt-in to cut email noise. Left unticked (the default) the
  // on_assignment_insert trigger skips the email; tick it to email the teacher.
  const [notifyTeacher, setNotifyTeacher] = React.useState(false);
  // Free-text note about the student for the teacher (v81). Rides on the
  // confirmation email above; ignored when notifyTeacher is unticked.
  const [noteForTeacher, setNoteForTeacher] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');

  // Filter: don't show students already assigned to this instructor.
  const alreadyAssignedIds = new Set(
    (data.assignments || [])
      .filter(a => a.instructorId === instructor.id && a.active)
      .map(a => a.studentId)
  );
  const availableStudents = (data.students || []).filter(s => !alreadyAssignedIds.has(s.id));

  // When a student is picked, set studentHourly from their negotiated rate
  // (or fall back to the instructor's listed rate). Both fields stay editable.
  React.useEffect(() => {
    if (!studentId) { setStudentHourly(''); return; }
    const s = (data.students || []).find(x => x.id === studentId);
    if (!s) return;
    const rate = s.hourlyRate != null ? s.hourlyRate : (instructor.rate || 80);
    setStudentHourly(rate);
  }, [studentId, data.students, instructor.rate]);

  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 submit = async (e) => {
    e.preventDefault();
    if (!studentId) { setError('Pick a student.'); return; }
    setBusy(true); setError('');
    try {
      await data.quickAssign({
        studentId, instructorId: instructor.id,
        studentHourly, teacherHourly,
        notifyTeacher,
        notes: noteForTeacher.trim(),
      });
      onClose();
    } catch (e2) { setError(e2.message || 'Could not assign.'); }
    finally { setBusy(false); }
  };

  const margin = Math.max(0, Number(studentHourly) - Number(teacherHourly));

  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:14, padding:'26px', width:460, boxShadow:'0 20px 60px rgba(0,0,0,0.18)', fontFamily:"'Plus Jakarta Sans', sans-serif", maxHeight:'92vh', overflowY:'auto' }} onClick={e=>e.stopPropagation()}>
        <div style={{ fontWeight:700, fontSize:16, color:'oklch(18% 0.03 265)', marginBottom:6 }}>Assign student to {instructor.name}</div>
        <div style={{ fontSize:12, color:'oklch(58% 0.03 265)', marginBottom:18 }}>Pick a student and set the hourly rate. We'll pro-rate 30/45/90-min lessons automatically.</div>
        {availableStudents.length === 0 ? (
          <>
            <div style={{ fontSize:13, color:'oklch(48% 0.04 265)', lineHeight:1.6, marginBottom:18 }}>
              No unassigned students yet. Add a student in the <strong>Students</strong> tab first, then come back here.
            </div>
            <button type="button" onClick={onClose} style={{ width:'100%', padding:'11px 0', background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>OK</button>
          </>
        ) : (
          <form onSubmit={submit}>
            <div style={{ marginBottom:14 }}>
              <label style={lbl}>Student</label>
              <select value={studentId} onChange={e=>setStudentId(e.target.value)} required style={fld}>
                <option value="">— Pick a student —</option>
                {availableStudents.map(s => (
                  <option key={s.id} value={s.id}>
                    {s.name} {s.hourlyRate != null ? `· $${s.hourlyRate}/hr` : ''}
                  </option>
                ))}
              </select>
            </div>
            {/* Pay fields are READ-ONLY on the assign flow — Joe asked for
                these to be visible-but-locked so they can't get changed by
                accident. Edit them later from the student row or assignment
                edit screen. */}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:8 }}>
              <div>
                <label style={lbl}>Student pays ($/hr) <span style={{ fontWeight:500, color:'oklch(60% 0.03 265)', textTransform:'none', letterSpacing:0 }}>· read-only</span></label>
                <input type="number" value={studentHourly} readOnly tabIndex={-1} style={{ ...fld, background:'oklch(96% 0.005 265)', color:'oklch(45% 0.03 265)', cursor:'not-allowed' }} />
              </div>
              <div>
                <label style={lbl}>Teacher gets ($/hr) <span style={{ fontWeight:500, color:'oklch(60% 0.03 265)', textTransform:'none', letterSpacing:0 }}>· read-only</span></label>
                <input type="number" value={teacherHourly} readOnly tabIndex={-1} style={{ ...fld, background:'oklch(96% 0.005 265)', color:'oklch(45% 0.03 265)', cursor:'not-allowed' }} />
              </div>
            </div>
            <div style={{ fontSize:11, color:'oklch(56% 0.03 265)', marginBottom:8, fontStyle:'italic' }}>
              Rates come from the student's profile. Edit them there if they need to change.
            </div>
            <div style={{ fontSize:12, color: margin > 0 ? 'oklch(30% 0.13 150)' : 'oklch(40% 0.18 25)', marginBottom:14, fontWeight:600 }}>
              Margin: ${margin}/hr {margin <= 0 && '⚠ check teacher rate'}
            </div>
            <div style={{ marginBottom:18 }}>
              <label style={lbl}>Note for {instructor.name?.split(' ')[0] || 'teacher'} about this student <span style={{ fontWeight:500, color:'oklch(60% 0.03 265)', textTransform:'none', letterSpacing:0 }}>· optional</span></label>
              <textarea
                value={noteForTeacher}
                onChange={e => setNoteForTeacher(e.target.value)}
                placeholder="Level, goals, scheduling quirks, anything the teacher should know before the first lesson."
                rows={3}
                style={{ ...fld, resize:'vertical', minHeight:80, fontFamily:"'Plus Jakarta Sans', sans-serif" }}
              />
              <div style={{ fontSize:11, color:'oklch(58% 0.03 265)', marginTop:4 }}>
                Saved to the assignment and visible on the teacher's dashboard. Also included in the confirmation email if you tick the box below.
              </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>}
            <label style={{ display:'flex', alignItems:'flex-start', gap:9, fontSize:13, color:'oklch(28% 0.04 265)', marginBottom:14, cursor:'pointer', userSelect:'none' }}>
              <input
                type="checkbox"
                checked={notifyTeacher}
                onChange={e => setNotifyTeacher(e.target.checked)}
                style={{ marginTop:3, width:16, height:16, accentColor:'oklch(22% 0.06 265)', cursor:'pointer', flexShrink:0 }}
              />
              <span>
                <strong style={{ fontWeight:600 }}>Email {instructor.name?.split(' ')[0] || 'teacher'} a confirmation</strong>
                <span style={{ display:'block', fontSize:11, color:'oklch(56% 0.03 265)', marginTop:2 }}>
                  Off by default. Tick to send the "you have a new student" email{noteForTeacher.trim() ? ', including the note above' : ''}. Otherwise the teacher is assigned without an email.
                </span>
              </span>
            </label>
            <div style={{ display:'flex', gap:10 }}>
              <button type="submit" disabled={busy || !studentId} style={{ flex:1, background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:9, padding:'11px 0', fontWeight:600, fontSize:14, cursor:busy?'wait':'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity:busy?0.7:1 }}>
                {busy ? 'Assigning…' : 'Assign student'}
              </button>
              <button type="button" onClick={onClose} style={{ padding:'11px 16px', background:'oklch(95% 0.01 265)', border:'none', borderRadius:9, fontSize:13, cursor:'pointer', color:'oklch(46% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>Cancel</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};


Object.assign(window, {
  AIAddStudentModal,
  AIAssignStudentModal,
});
// AIBookLessonModal + AIConfirmDelete now live in
// admin-instructors-modals-3.jsx (loaded after this file).
