const { useState: useStateAU, useRef: useRefAU } = React;

var FI_AU = { width: '100%', padding: '10px 14px', border: '1.5px solid #e5e7eb', borderRadius: 8, fontSize: 14, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box', color: '#1e293b' };
var BP_AU = { background: '#1c79b4', color: 'white', border: 'none', borderRadius: 8, padding: '10px 22px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' };
var BG_AU = { background: '#c4b400', color: '#1c79b4', border: 'none', borderRadius: 8, padding: '8px 18px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' };
var BGH_AU = { background: '#f1f5f9', color: '#475569', border: 'none', borderRadius: 6, padding: '6px 12px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' };
var BD_AU = { background: '#fee2e2', color: '#dc2626', border: 'none', borderRadius: 6, padding: '6px 10px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' };

function AdminUsers() {
  const [modal, setModal] = useStateAU(null);
  const [form, setForm] = useStateAU({});
  const [search, setSearch] = useStateAU('');
  const [tick, setTick] = useStateAU(0);
  const [viewProfile, setViewProfile] = useStateAU(null);
  const fileInputRef = useRefAU(null);

  function refresh() { setTick(function (t) { return t + 1; }); }
  var students = getUsers().filter(function (u) { return u.rol === 'estudiante'; });

  function sf(k, v) { setForm(function (f) { return Object.assign({}, f, { [k]: v }); }); }

  function openAdd() { setForm({ rol: 'estudiante', activo: true, photoB64: '' }); setModal('add'); }
  function openEdit(u) { setForm(Object.assign({}, u, { photoB64: getStudentPhoto(u.id) || '' })); setModal('edit'); }

  function handlePhotoSelect(e) {
    var file = e.target.files && e.target.files[0];
    if (!file) return;
    var reader = new FileReader();
    reader.onload = function (ev) { sf('photoB64', ev.target.result); };
    reader.readAsDataURL(file);
    e.target.value = '';
  }

  function save() {
    if (!form.nombre || !form.email || !form.password) { window.alert('Nombre, correo y contraseña son obligatorios.'); return; }
    var photoB64 = form.photoB64 !== undefined ? form.photoB64 : '';
    var userForm = Object.assign({}, form);
    delete userForm.photoB64;

    if (modal === 'add') {
      if (typeof window.sbCreateUser === 'function') {
        window.sbCreateUser(userForm.email, userForm.password, userForm.nombre, userForm.rol || 'estudiante', userForm.empresa || '', userForm.cargo || '')
          .then(function (res) {
            if (res.error) { window.alert('Error al crear usuario: ' + res.error.message); return; }
            var newId = res.data.id;
            var nu = Object.assign({}, userForm, { id: newId, fechaCreacion: new Date().toISOString().split('T')[0] });
            var all = getUsers();
            saveUsers(all.concat([nu]));
            saveStudentPhoto(newId, photoB64);
            if (window.pushAdminNotif) {
              window.pushAdminNotif({ id: 'notif_newstu_' + newId + '_' + Date.now(), type: 'new_student', text: 'Nuevo estudiante registrado: ' + nu.nombre + (nu.empresa ? ' (' + nu.empresa + ')' : '') + '.', time: Date.now(), read: false, studentId: newId, studentName: nu.nombre });
            }
            setModal(null); refresh();
          });
      } else {
        var all = getUsers();
        var nu = Object.assign({}, userForm, { id: 'u' + Date.now(), fechaCreacion: new Date().toISOString().split('T')[0] });
        saveUsers(all.concat([nu]));
        saveStudentPhoto(nu.id, photoB64);
        if (window.pushAdminNotif) {
          window.pushAdminNotif({ id: 'notif_newstu_' + nu.id + '_' + Date.now(), type: 'new_student', text: 'Nuevo estudiante registrado: ' + nu.nombre + (nu.empresa ? ' (' + nu.empresa + ')' : '') + '.', time: Date.now(), read: false, studentId: nu.id, studentName: nu.nombre });
        }
        setModal(null); refresh();
      }
    } else {
      var all = getUsers();
      saveUsers(all.map(function (u) { return u.id === userForm.id ? userForm : u; }));
      saveStudentPhoto(userForm.id, photoB64);
      if (typeof window.sbUpdateProfile === 'function') {
        window.sbUpdateProfile(userForm.id, { nombre: userForm.nombre, email: userForm.email, rol: userForm.rol, empresa: userForm.empresa || '', cargo: userForm.cargo || '', activo: userForm.activo });
        if (userForm.password) window.sbUpdatePassword(userForm.id, userForm.password);
      }
      setModal(null); refresh();
    }
  }

  function toggle(id) {
    var toggled = getUsers().map(function (u) { return u.id === id ? Object.assign({}, u, { activo: !u.activo }) : u; });
    saveUsers(toggled);
    var target = toggled.find(function (u) { return u.id === id; });
    if (target && typeof window.sbUpdateProfile === 'function') window.sbUpdateProfile(id, { activo: target.activo });
    refresh();
  }

  function del(id) {
    if (!window.confirm('¿Eliminar este estudiante permanentemente?')) return;
    saveUsers(getUsers().filter(function (u) { return u.id !== id; }));
    if (typeof window.sbDeleteUser === 'function') {
      window.sbDeleteUser(id).then(function (res) {
        if (res && res.error) console.error('[Supabase] Error eliminando usuario:', res.error.message);
      });
    }
    refresh();
  }

  function exportToExcel() {
    if (typeof XLSX === 'undefined') {
      window.alert('La librería XLSX no está disponible. Recargue la página e intente de nuevo.');
      return;
    }
    var mods = getModules();
    var totalLes = mods.reduce(function (a, m) { return a + m.lecciones.length; }, 0);
    var rows = students.map(function (u) {
      var profile = getProfileData(u.id);
      var prog = getProgress(u.id);
      var done = mods.reduce(function (a, m) { return a + m.lecciones.filter(function (l) { return prog[l.id]; }).length; }, 0);
      var pct = totalLes > 0 ? Math.round(done / totalLes * 100) : 0;
      return {
        'Nombre completo': u.nombre,
        'Número de documento': profile.documento || '',
        'Correo electrónico': u.email,
        'WhatsApp': profile.whatsapp || '',
        'Ciudad de residencia': profile.ciudad || '',
        'Empresa': profile.empresa || u.empresa || '',
        'Cargo': profile.cargo || u.cargo || '',
        'Sector': profile.sector === 'Otro' ? (profile.sectorOtro || 'Otro') : (profile.sector || ''),
        'Años de experiencia SST': profile.anosExperiencia || '',
        'Licencia SST vigente': profile.tieneLicencia === 'si' ? 'Sí' : profile.tieneLicencia === 'no' ? 'No' : '',
        'Cómo se enteró': profile.comoSeEntero === 'Otro' ? (profile.comoSeEnteroOtro || 'Otro') : (profile.comoSeEntero || ''),
        'Estado': u.activo ? 'Activo' : 'Inactivo',
        'Progreso (%)': pct,
        'Fecha de registro': u.fechaCreacion || ''
      };
    });
    var ws = XLSX.utils.json_to_sheet(rows);
    var colKeys = Object.keys(rows[0] || {});
    ws['!cols'] = colKeys.map(function (k) {
      var max = k.length;
      rows.forEach(function (r) { var v = String(r[k] || ''); if (v.length > max) max = v.length; });
      return { wch: Math.min(max + 2, 40) };
    });
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Estudiantes');
    XLSX.writeFile(wb, 'Estudiantes_ASSYST_SST.xlsx');
  }

  var filtered = students.filter(function (u) {
    var q = search.toLowerCase();
    return !q || u.nombre.toLowerCase().includes(q) || u.email.toLowerCase().includes(q) || (u.empresa || '').toLowerCase().includes(q);
  });

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 800, color: '#1c79b4' }}>Estudiantes</h2>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: '#6b7280' }}>{students.length} registrados · {students.filter(function (u) { return u.activo; }).length} activos</p>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <button
            onClick={exportToExcel}
            style={{ display: 'flex', alignItems: 'center', gap: 7, background: '#16a34a', color: 'white', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', transition: 'background .15s' }}
            onMouseOver={function (e) { e.currentTarget.style.background = '#15803d'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = '#16a34a'; }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
              <polyline points="7 10 12 15 17 10"></polyline>
              <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
            Exportar a Excel
          </button>
          <button style={BG_AU} onClick={openAdd}>+ Nuevo estudiante</button>
        </div>
      </div>

      <input value={search} onChange={function (e) { setSearch(e.target.value); }} placeholder="Buscar por nombre, correo o empresa..." style={Object.assign({}, FI_AU, { maxWidth: 380, marginBottom: 16 })} />

      <div style={{ background: 'white', borderRadius: 12, border: '1px solid #e5e7eb', overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f8fafc', borderBottom: '2px solid #e5e7eb' }}>
              {['Estudiante', 'Empresa / Cargo', 'Correo', 'Estado', 'Acciones'].map(function (h) {
                return <th key={h} style={{ padding: '12px 16px', textAlign: 'left', fontWeight: 700, color: '#6b7280', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{h}</th>;
              })}
            </tr>
          </thead>
          <tbody>
            {filtered.map(function (u, i) {
              return (
                <tr key={u.id} style={{ borderBottom: i < filtered.length - 1 ? '1px solid #f1f5f9' : 'none' }}>
                  <td style={{ padding: '13px 16px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <StudentAvatar userId={u.id} userName={u.nombre} size={34} style={{ border: '2px solid #e5e7eb' }} />
                      <span style={{ fontWeight: 600, color: '#1e293b' }}>{u.nombre}</span>
                    </div>
                  </td>
                  <td style={{ padding: '13px 16px' }}>
                    <div style={{ fontSize: 13, color: '#374151' }}>{u.empresa}</div>
                    <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>{u.cargo}</div>
                  </td>
                  <td style={{ padding: '13px 16px', color: '#6b7280' }}>{u.email}</td>
                  <td style={{ padding: '13px 16px' }}>
                    <span style={{ padding: '4px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700, background: u.activo ? '#dcfce7' : '#fee2e2', color: u.activo ? '#15803d' : '#dc2626' }}>
                      {u.activo ? 'Activo' : 'Inactivo'}
                    </span>
                  </td>
                  <td style={{ padding: '13px 16px' }}>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      <button style={Object.assign({}, BGH_AU, { color: '#1c79b4', background: 'rgba(28,121,180,.08)' })} onClick={function () { setViewProfile(u); }}>Perfil</button>
                      <button style={BGH_AU} onClick={function () { openEdit(u); }}>Editar</button>
                      <button style={Object.assign({}, BGH_AU, { background: u.activo ? '#fff7ed' : '#f0fdf4', color: u.activo ? '#c2410c' : '#15803d' })} onClick={function () { toggle(u.id); }}>
                        {u.activo ? 'Desactivar' : 'Activar'}
                      </button>
                      <button style={BD_AU} onClick={function () { del(u.id); }}>×</button>
                    </div>
                  </td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan={5} style={{ textAlign: 'center', padding: 36, color: '#d1d5db', fontSize: 14 }}>Sin resultados</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {viewProfile && (function () {
        var p = getProfileData(viewProfile.id);
        var sectorDisplay = p.sector === 'Otro' ? (p.sectorOtro || '(sin especificar)') : (p.sector || '');
        var comoDisplay = p.comoSeEntero === 'Otro' ? (p.comoSeEnteroOtro || '(sin especificar)') : (p.comoSeEntero || '');
        var rows = [
          ['Documento', p.documento],
          ['WhatsApp', p.whatsapp],
          ['Ciudad', p.ciudad],
          ['Empresa', p.empresa || viewProfile.empresa],
          ['Cargo', p.cargo || viewProfile.cargo],
          ['Sector', sectorDisplay],
          ['Años de exp. SST', p.anosExperiencia],
          ['Licencia SST vigente', p.tieneLicencia === 'si' ? 'Sí ✓' : p.tieneLicencia === 'no' ? 'No' : ''],
          ['Cómo se enteró', comoDisplay]
        ];
        return (
          <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,61,94,.75)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
            <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 520, maxHeight: '88vh', overflowY: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,.28)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '22px 28px', borderBottom: '1px solid #f1f5f9', position: 'sticky', top: 0, background: 'white', borderRadius: '16px 16px 0 0', zIndex: 1 }}>
                <div>
                  <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: '#1c79b4' }}>Perfil de estudiante</h3>
                  <p style={{ margin: '3px 0 0', fontSize: 12, color: '#9ca3af' }}>Datos completados por el estudiante</p>
                </div>
                <button onClick={function () { setViewProfile(null); }} style={{ background: 'none', border: 'none', fontSize: 24, cursor: 'pointer', color: '#9ca3af', lineHeight: 1 }}>×</button>
              </div>
              <div style={{ padding: '20px 28px 24px' }}>
                <div style={{ background: '#f8fafc', borderRadius: 10, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
                  <StudentAvatar userId={viewProfile.id} userName={viewProfile.nombre} size={40} style={{ border: '2px solid #e5e7eb' }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 700, color: '#1e293b' }}>{viewProfile.nombre}</div>
                    <div style={{ fontSize: 12, color: '#9ca3af' }}>{viewProfile.email}</div>
                  </div>
                  <span style={{ fontSize: 10, fontWeight: 700, color: viewProfile.activo ? '#15803d' : '#dc2626', background: viewProfile.activo ? '#dcfce7' : '#fee2e2', padding: '4px 10px', borderRadius: 20 }}>{viewProfile.activo ? 'Activo' : 'Inactivo'}</span>
                </div>
                {rows.map(function (row) {
                  return (
                    <div key={row[0]} style={{ padding: '9px 0', borderBottom: '1px solid #f9fafb', display: 'grid', gridTemplateColumns: '160px 1fr', gap: 8, alignItems: 'start' }}>
                      <span style={{ fontSize: 10, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em', paddingTop: 2 }}>{row[0]}</span>
                      <span style={{ fontSize: 13, color: row[1] ? '#1e293b' : '#d1d5db' }}>{row[1] || '—'}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        );
      })()}

      {modal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(10,61,94,.75)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
          <div style={{ background: 'white', borderRadius: 16, width: '100%', maxWidth: 500, boxShadow: '0 24px 64px rgba(0,0,0,.28)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '22px 28px', borderBottom: '1px solid #f1f5f9' }}>
              <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: '#1c79b4' }}>{modal === 'add' ? 'Nuevo estudiante' : 'Editar estudiante'}</h3>
              <button onClick={function () { setModal(null); }} style={{ background: 'none', border: 'none', fontSize: 24, cursor: 'pointer', color: '#9ca3af', lineHeight: 1 }}>×</button>
            </div>
            <div style={{ padding: '24px 28px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {[['Nombre completo', 'nombre', 'text', 'Ej: María García', 'span 2'],
                ['Correo electrónico', 'email', 'email', 'maria@empresa.com', 'span 2'],
                ['Empresa', 'empresa', 'text', 'Nombre de la empresa', ''],
                ['Cargo', 'cargo', 'text', 'Ej: Técnico SST', ''],
                ['Contraseña', 'password', 'password', 'Mínimo 6 caracteres', 'span 2']
              ].map(function (row) {
                return (
                  <div key={row[1]} style={{ gridColumn: row[4] || 'span 1' }}>
                    <label style={{ display: 'block', fontSize: 10, fontWeight: 700, color: '#6b7280', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{row[0]}</label>
                    <input type={row[2]} placeholder={row[3]} value={form[row[1]] || ''} onChange={function (e) { sf(row[1], e.target.value); }} style={FI_AU} />
                  </div>
                );
              })}
              <div style={{ gridColumn: 'span 2', borderTop: '1px dashed #e5e7eb', paddingTop: 16, marginTop: 4 }}>
                <label style={{ display: 'block', fontSize: 10, fontWeight: 700, color: '#6b7280', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.07em' }}>Foto de perfil</label>
                <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                  {/* Preview circular */}
                  <div style={{ flexShrink: 0 }}>
                    {form.photoB64 ? (
                      <img
                        src={form.photoB64}
                        alt="Vista previa"
                        style={{ width: 70, height: 70, borderRadius: '50%', objectFit: 'cover', border: '2.5px solid #e5e7eb', display: 'block' }}
                      />
                    ) : (
                      <div style={{
                        width: 70, height: 70, borderRadius: '50%',
                        background: getAvatarPalette(form.nombre || '').bg,
                        color: getAvatarPalette(form.nombre || '').fg,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 24, fontWeight: 800, letterSpacing: '0.02em',
                        fontFamily: "'Montserrat',sans-serif"
                      }}>
                        {getAvatarInitials(form.nombre || '?')}
                      </div>
                    )}
                  </div>
                  {/* Controles */}
                  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/*"
                      style={{ display: 'none' }}
                      onChange={handlePhotoSelect}
                    />
                    <button
                      type="button"
                      onClick={function () { fileInputRef.current && fileInputRef.current.click(); }}
                      style={{ display: 'inline-flex', alignItems: 'center', gap: 7, background: '#1c79b4', color: 'white', border: 'none', borderRadius: 8, padding: '9px 16px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', width: 'fit-content' }}
                    >
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                        <polyline points="17 8 12 3 7 8"/>
                        <line x1="12" y1="3" x2="12" y2="15"/>
                      </svg>
                      Subir foto
                    </button>
                    {form.photoB64 && (
                      <button
                        type="button"
                        onClick={function () { sf('photoB64', ''); }}
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: '#fee2e2', color: '#dc2626', border: 'none', borderRadius: 8, padding: '7px 14px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', width: 'fit-content' }}
                      >
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="3 6 5 6 21 6"/>
                          <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
                          <path d="M10 11v6M14 11v6"/>
                        </svg>
                        Eliminar foto
                      </button>
                    )}
                    <p style={{ margin: 0, fontSize: 10.5, color: '#9ca3af', lineHeight: 1.5 }}>
                      JPG, PNG o WebP · La imagen se guarda localmente en base64
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', padding: '14px 28px', borderTop: '1px solid #f1f5f9' }}>
              <button style={BGH_AU} onClick={function () { setModal(null); }}>Cancelar</button>
              <button style={BP_AU} onClick={save}>Guardar</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AdminUsers = AdminUsers;
