// Admin panel: users, courses

function AdminPanel(){
  const store = useStore();
  const toast = useToast();
  const [tab, setTab] = React.useState('students'); // students | employees | courses
  const [editingUser, setEditingUser] = React.useState(null);
  const [creatingRole, setCreatingRole] = React.useState(null);
  const [editingCourse, setEditingCourse] = React.useState(null);
  const [creatingCourse, setCreatingCourse] = React.useState(false);
  const [confirm, setConfirm] = React.useState(null);

  const students = store.state.users.filter(u => u.role === 'student');
  const employees = store.state.users.filter(u => u.role === 'employee');
  const admins = store.state.users.filter(u => u.role === 'admin');

  const totalClasses = store.state.classes.length;
  const totalMeetings = store.state.meetings.length;

  function saveUser(payload){
    if(editingUser){
      store.updateUser(editingUser.id, payload);
      toast('User updated');
    } else {
      store.createUser(payload);
      toast(`${payload.role[0].toUpperCase()+payload.role.slice(1)} created`);
    }
  }
  function saveCourse(payload){
    const { students, ...courseData } = payload;
    if(editingCourse){
      store.updateCourse(editingCourse.id, courseData).then(() => {
        if (students) store.assignCourseStudents(editingCourse.id, students);
      });
      toast('Course updated');
    } else {
      store.createCourse(courseData).then(courseId => {
        if (students) store.assignCourseStudents(courseId, students);
      });
      toast('Course created');
    }
  }

  function toggleBlockUser(u){
    setConfirm({
      title: u.isBlocked ? `Unblock ${u.name}?` : `Block ${u.name}?`,
      message: u.isBlocked ? `They will be able to log in again.` : `They will immediately be prevented from logging in.`,
      onConfirm: () => { store.updateUser(u.id, { isBlocked: !u.isBlocked }); toast(`User ${u.isBlocked ? 'unblocked' : 'blocked'}`); },
      danger: !u.isBlocked,
      confirmLabel: u.isBlocked ? 'Unblock' : 'Block'
    });
  }

  function deleteUser(u){
    setConfirm({
      title: `Remove ${u.name}?`,
      message: `Their account will be deleted and they'll be removed from any meeting invites. This can't be undone.`,
      onConfirm: () => { store.deleteUser(u.id); toast('User removed'); },
    });
  }
  function deleteCourse(c){
    const studentCount = store.state.users.filter(u => (u.courses||[]).includes(c.id)).length;
    const classCount = store.state.classes.filter(cl => cl.courseId === c.id).length;
    setConfirm({
      title: `Delete ${c.name}?`,
      message: `This will also delete ${classCount} class${classCount===1?'':'es'} and unassign ${studentCount} student${studentCount===1?'':'s'}.`,
      onConfirm: () => { store.deleteCourse(c.id); toast('Course deleted'); },
    });
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Admin panel</h1>
          <div className="page-sub">Manage users, courses and assignments.</div>
        </div>
      </div>

      <div className="stat-grid">
        <div className="stat">
          <div className="k">Students</div>
          <div className="v">{students.length}</div>
          <div className="d">{students.filter(s=>s.courses?.length).length} enrolled in a course</div>
        </div>
        <div className="stat">
          <div className="k">Employees</div>
          <div className="v">{employees.length}</div>
          <div className="d">{admins.length} admin{admins.length===1?'':'s'}</div>
        </div>
        <div className="stat">
          <div className="k">Courses</div>
          <div className="v">{store.state.courses.length}</div>
          <div className="d">{totalClasses} class{totalClasses===1?'':'es'} scheduled</div>
        </div>
        <div className="stat">
          <div className="k">Online Meetings</div>
          <div className="v">{totalMeetings}</div>
          <div className="d">across all employees</div>
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="tabs" style={{ background:'transparent', padding:0, gap: 4 }}>
            {[
              { k:'students', label:'Students', count: students.length, icon:'grad' },
              { k:'employees', label:'Employees', count: employees.length, icon:'users' },
              { k:'courses', label:'Courses', count: store.state.courses.length, icon:'book' },
            ].map(t => (
              <button key={t.k} className={`tab ${tab===t.k?'is-active':''}`} onClick={()=>setTab(t.k)}>
                <Icon name={t.icon} size={14} /> {t.label} <span className="pill">{t.count}</span>
              </button>
            ))}
          </div>
          <div style={{ display:'flex', gap: 8 }}>
            {tab === 'students' && <button className="btn accent" onClick={()=>{ setEditingUser(null); setCreatingRole('student'); }}><Icon name="plus" /> Add student</button>}
            {tab === 'employees' && <button className="btn accent" onClick={()=>{ setEditingUser(null); setCreatingRole('employee'); }}><Icon name="plus" /> Add employee</button>}
            {tab === 'courses' && <button className="btn accent" onClick={()=>{ setEditingCourse(null); setCreatingCourse(true); }}><Icon name="plus" /> New course</button>}
          </div>
        </div>

        {tab === 'students' && (
          <UserList users={students} courses={store.state.courses} onEdit={u => { setEditingUser(u); setCreatingRole(null); }} onDelete={deleteUser} onToggleBlock={toggleBlockUser} emptyLabel="No students yet" />
        )}
        {tab === 'employees' && (
          <UserList users={employees.concat(admins)} courses={store.state.courses} showRoleTag onEdit={u => { setEditingUser(u); setCreatingRole(null); }} onDelete={deleteUser} onToggleBlock={toggleBlockUser} emptyLabel="No employees yet" />
        )}
        {tab === 'courses' && (
          <CourseList courses={store.state.courses} users={store.state.users} classes={store.state.classes}
            onEdit={c => setEditingCourse(c)} onDelete={deleteCourse} />
        )}
      </div>

      <UserForm
        open={!!editingUser || !!creatingRole}
        onClose={() => { setEditingUser(null); setCreatingRole(null); }}
        initial={editingUser}
        defaultRole={creatingRole}
        onSave={saveUser}
      />
      <CourseForm
        open={!!editingCourse || creatingCourse}
        onClose={() => { setEditingCourse(null); setCreatingCourse(false); }}
        initial={editingCourse}
        onSave={saveCourse}
      />
      <ConfirmDialog
        open={!!confirm}
        title={confirm?.title || ''}
        message={confirm?.message || ''}
        confirmLabel={confirm?.confirmLabel || 'Delete'}
        danger={confirm?.danger !== false}
        onClose={() => setConfirm(null)}
        onConfirm={() => confirm?.onConfirm?.()}
      />
    </div>
  );
}

function UserList({ users, courses, onEdit, onDelete, onToggleBlock, showRoleTag, emptyLabel }){
  if(users.length === 0){
    return (
      <div style={{ padding:'48px 24px', textAlign:'center' }}>
        <div style={{ fontSize:32, marginBottom:8 }}>👤</div>
        <div style={{ fontWeight:600, color:'var(--ink-2)', marginBottom:4 }}>{emptyLabel}</div>
        <div style={{ fontSize:12.5, color:'var(--ink-3)' }}>Use the button above to create one.</div>
      </div>
    );
  }
  return (
    <div>
      {users.map(u => {
        const assigned = (u.courses||[]).map(cid => courses.find(c => c.id === cid)).filter(Boolean);
        return (
          <div className="list-row" key={u.id}>
            <div className="avatar lg" style={{ opacity: u.isBlocked ? 0.4 : 1 }}>{initials(u.name)}</div>
            <div style={{ minWidth: 0 }}>
              <div className="name" style={{ display:'flex', alignItems:'center', gap:6 }}>
                <span style={{ textDecoration: u.isBlocked ? 'line-through' : 'none', color: u.isBlocked ? 'var(--ink-3)' : 'inherit' }}>{u.name}</span>
                {u.isBlocked && <span className="tag warn">Blocked</span>}
                {showRoleTag && <span className="tag" style={{ background: u.role==='admin'?'var(--accent-soft)':'var(--surface-2)', color: u.role==='admin'?'var(--accent)':'var(--ink-2)' }}>{u.role}</span>}
              </div>
              <div className="email">{u.email}</div>
              {u.role === 'student' && (
                <div className="courses" style={{ marginTop:5 }}>
                  {assigned.length === 0
                    ? <span className="ck" style={{ color:'var(--ink-3)', background:'transparent', border:'1px dashed var(--line-2)' }}>No courses assigned</span>
                    : assigned.map(c => <span key={c.id} className="ck" style={{ background: c.color+'18', border:`1px solid ${c.color}40`, color: c.color }}>{c.code}</span>)
                  }
                </div>
              )}
            </div>
            <div style={{ display:'flex', gap:4 }}>
              <button className={`btn sm ghost${u.isBlocked?' danger':''}`} title={u.isBlocked?'Unblock':'Block'} onClick={() => onToggleBlock(u)}>
                <Icon name={u.isBlocked?'unlock':'lock'} size={13} />
              </button>
              <button className="btn sm ghost" title="Edit" onClick={() => onEdit(u)}><Icon name="edit" size={13} /></button>
              <button className="btn sm ghost danger" title="Remove" onClick={() => onDelete(u)}><Icon name="trash" size={13} /></button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function CourseList({ courses, users, classes, onEdit, onDelete }){
  if(courses.length === 0){
    return (
      <div style={{ padding:'48px 24px', textAlign:'center' }}>
        <div style={{ fontSize:32, marginBottom:8 }}>📚</div>
        <div style={{ fontWeight:600, color:'var(--ink-2)', marginBottom:4 }}>No courses yet</div>
        <div style={{ fontSize:12.5, color:'var(--ink-3)' }}>Create your first course to get started.</div>
      </div>
    );
  }
  return (
    <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(260px,1fr))', gap:12, padding:16 }}>
      {courses.map(c => {
        const studentCount = users.filter(u => (u.courses||[]).includes(c.id)).length;
        const classCount = classes.filter(cl => cl.courseId === c.id).length;
        return (
          <div key={c.id} style={{
            background:'var(--surface)', border:`1px solid var(--line)`, borderRadius:'var(--radius-lg)',
            overflow:'hidden', display:'flex', flexDirection:'column',
            boxShadow:'var(--shadow-sm)',
          }}>
            <div style={{ height:6, background: c.color }} />
            <div style={{ padding:'14px 16px', flex:1 }}>
              <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:8 }}>
                <div>
                  <div style={{ fontWeight:700, fontSize:14.5, letterSpacing:'-0.005em', marginBottom:2 }}>{c.name}</div>
                  <div style={{ fontFamily:"'JetBrains Mono',monospace", fontSize:11.5, color:'var(--ink-3)', fontWeight:600 }}>{c.code}</div>
                </div>
                <div style={{ display:'flex', gap:3 }}>
                  <button className="btn sm ghost" title="Edit" onClick={() => onEdit(c)}><Icon name="edit" size={13} /></button>
                  <button className="btn sm ghost danger" title="Delete" onClick={() => onDelete(c)}><Icon name="trash" size={13} /></button>
                </div>
              </div>
              <div style={{ display:'flex', gap:8, marginTop:12 }}>
                <div style={{ flex:1, background:'var(--surface-2)', borderRadius:8, padding:'8px 10px', textAlign:'center' }}>
                  <div style={{ fontFamily:"'Fraunces',serif", fontSize:20, fontWeight:500, lineHeight:1 }}>{studentCount}</div>
                  <div style={{ fontSize:11, color:'var(--ink-3)', fontWeight:600, marginTop:2, textTransform:'uppercase', letterSpacing:'0.04em' }}>Students</div>
                </div>
                <div style={{ flex:1, background:'var(--surface-2)', borderRadius:8, padding:'8px 10px', textAlign:'center' }}>
                  <div style={{ fontFamily:"'Fraunces',serif", fontSize:20, fontWeight:500, lineHeight:1 }}>{classCount}</div>
                  <div style={{ fontSize:11, color:'var(--ink-3)', fontWeight:600, marginTop:2, textTransform:'uppercase', letterSpacing:'0.04em' }}>Classes</div>
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { AdminPanel });
