// ============================================================
// Módulo de Gestión de Usuarios
// ============================================================
const AREAS = ['Digitalización', 'Edición', 'Control de Calidad', 'Conversión', 'Supervisión', 'Administración'];
const PUESTOS = ['Operador', 'Analista', 'Coordinador', 'Supervisor', 'Jefe de área', 'Director'];

const GestionUsuariosLocal = ({ usuarios, onUpdate, onCreate, onDelete }) => {
  const [editando, setEditando] = useState(null);
  const [creando, setCreando] = useState(false);
  const [q, setQ] = useState('');

  const filtrados = usuarios.filter(u =>
    !q || u.nombre.toLowerCase().includes(q.toLowerCase()) || u.id.toLowerCase().includes(q.toLowerCase())
  );

  return (
    <div className="stack">
      <div className="card">
        <div className="card-header">
          <Icon name="users" size={16} style={{ color: 'var(--text-2)' }}/>
          <div>
            <div className="card-title">Gestión de usuarios y perfiles</div>
            <div className="card-subtitle">Administra nombres, áreas, puestos, credenciales y roles del sistema</div>
          </div>
          <div className="spacer"/>
          <button className="btn btn-primary" onClick={() => setCreando(true)}>
            <Icon name="plus" size={14}/>
            Nuevo usuario
          </button>
        </div>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)', background: 'var(--surface-2)' }}>
          <div style={{ position: 'relative', maxWidth: 400 }}>
            <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)' }}/>
            <input
              type="text"
              className="input"
              placeholder="Buscar por nombre o usuario..."
              value={q}
              onChange={e => setQ(e.target.value)}
              style={{ paddingLeft: 32 }}
            />
          </div>
        </div>
        <div className="table-wrap" style={{ border: 'none', borderRadius: 0 }}>
          <table className="data">
            <thead>
              <tr>
                <th>Usuario</th>
                <th>Nombre completo</th>
                <th>Área</th>
                <th>Puesto</th>
                <th>Correo</th>
                <th>Roles asignados</th>
                <th>Password</th>
                <th style={{ textAlign: 'right' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {filtrados.map(u => (
                <tr key={u.id}>
                  <td>
                    <div className="row">
                      <Avatar user={u} size="sm"/>
                      <span className="text-mono text-sm">{u.id}</span>
                    </div>
                  </td>
                  <td style={{ fontWeight: 500 }}>{u.nombre}</td>
                  <td className="text-sm text-2">{u.area || '—'}</td>
                  <td className="text-sm text-2">{u.puesto || '—'}</td>
                  <td className="text-sm text-2 text-mono">{u.email || '—'}</td>
                  <td>
                    <div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
                      {u.roles.map(r => (
                        <span key={r} className="badge" style={{
                          background: APP_DATA.ROLES[r]?.color + '20',
                          color: APP_DATA.ROLES[r]?.color,
                          fontSize: 10,
                        }}>
                          {APP_DATA.ROLES[r]?.label}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td>
                    <span className="text-mono text-xs text-3">
                      {u.password ? '••••••••' : 'Sin definir'}
                    </span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <button className="btn btn-ghost btn-sm" onClick={() => setEditando(u)}>
                      Editar
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <UsuarioModal
        open={!!editando || creando}
        usuario={editando}
        onClose={() => { setEditando(null); setCreando(false); }}
        onSave={(data) => {
          if (editando) onUpdate(editando.id, data);
          else onCreate(data);
          setEditando(null); setCreando(false);
        }}
        onDelete={editando ? () => { onDelete(editando.id); setEditando(null); } : null}
      />
    </div>
  );
};

const UsuarioModal = ({ open, usuario, onClose, onSave, onDelete }) => {
  const [form, setForm] = useState({
    id: '', nombre: '', area: '', puesto: '', email: '', telefono: '',
    color: '#1e40af', iniciales: '', roles: [], password: '', confirmPassword: '',
    activo: true,
  });
  const [showPass, setShowPass] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);

  useEffect(() => {
    if (usuario) {
      setForm({
        id: usuario.id, nombre: usuario.nombre,
        area: usuario.area || '', puesto: usuario.puesto || '',
        email: usuario.email || '', telefono: usuario.telefono || '',
        color: usuario.color, iniciales: usuario.iniciales,
        roles: [...usuario.roles], password: usuario.password || '', confirmPassword: usuario.password || '',
        activo: usuario.activo !== false,
      });
    } else {
      setForm({
        id: '', nombre: '', area: '', puesto: '', email: '', telefono: '',
        color: '#1e40af', iniciales: '', roles: [], password: '', confirmPassword: '',
        activo: true,
      });
    }
    setConfirmDelete(false);
    setShowPass(false);
  }, [usuario, open]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const toggleRol = (r) => {
    setForm(f => ({
      ...f,
      roles: f.roles.includes(r) ? f.roles.filter(x => x !== r) : [...f.roles, r],
    }));
  };

  const generarIniciales = (nombre) => {
    const parts = nombre.trim().split(/\s+/);
    return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase();
  };

  const generarUsuario = (nombre) => {
    return nombre.toLowerCase().split(/\s+/)[0].normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z]/g, '');
  };

  const handleNombreChange = (v) => {
    setForm(f => ({
      ...f,
      nombre: v,
      iniciales: usuario ? f.iniciales : generarIniciales(v),
      id: usuario ? f.id : generarUsuario(v),
    }));
  };

  const puedeGuardar = form.nombre && form.id && form.roles.length > 0 &&
                       form.password && form.password === form.confirmPassword;

  const guardar = () => {
    if (!puedeGuardar) return;
    const { confirmPassword, ...data } = form;
    onSave(data);
  };

  const COLORES = ['#1e40af','#0f766e','#b45309','#4338ca','#be185d','#7e22ce','#c2410c','#15803d','#7c2d12','#0891b2'];

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={usuario ? `Editar perfil · ${usuario.nombre}` : 'Nuevo usuario'}
      maxWidth={640}
      footer={<>
        {usuario && onDelete && (
          confirmDelete ? (
            <>
              <span className="text-sm text-2" style={{ marginRight: 'auto' }}>¿Confirmar eliminación?</span>
              <button className="btn btn-ghost" onClick={() => setConfirmDelete(false)}>Cancelar</button>
              <button className="btn btn-danger" onClick={onDelete}>Sí, eliminar</button>
            </>
          ) : (
            <>
              <button className="btn btn-ghost" style={{ marginRight: 'auto', color: 'var(--danger)' }} onClick={() => setConfirmDelete(true)}>
                Eliminar usuario
              </button>
              <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
              <button className="btn btn-primary" onClick={guardar} disabled={!puedeGuardar}>Guardar cambios</button>
            </>
          )
        )}
        {!usuario && (
          <>
            <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
            <button className="btn btn-primary" onClick={guardar} disabled={!puedeGuardar}>Crear usuario</button>
          </>
        )}
      </>}
    >
      {/* Avatar preview */}
      <div className="row" style={{ padding: 14, background: 'var(--surface-2)', borderRadius: 8, marginBottom: 16 }}>
        <div className="avatar lg" style={{ background: form.color }}>
          {form.iniciales || '??'}
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 15 }}>{form.nombre || 'Nombre completo'}</div>
          <div className="text-sm text-2">{form.puesto || 'Puesto'} · {form.area || 'Área'}</div>
          <div className="text-xs text-3 text-mono mt-4">@{form.id || 'usuario'}</div>
        </div>
        <div>
          <div className="detail-label mb-4">Color</div>
          <div className="row" style={{ gap: 4, flexWrap: 'wrap', maxWidth: 130 }}>
            {COLORES.map(c => (
              <div
                key={c}
                onClick={() => set('color', c)}
                style={{
                  width: 20, height: 20, borderRadius: '50%', background: c,
                  cursor: 'pointer',
                  border: form.color === c ? '2px solid var(--text)' : '2px solid transparent',
                  boxShadow: form.color === c ? '0 0 0 1px white inset' : 'none',
                }}
              />
            ))}
          </div>
        </div>
      </div>

      <div className="detail-section-title mb-12">Datos personales</div>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
        <div className="field">
          <label className="field-label">Nombre completo *</label>
          <input className="input" value={form.nombre} onChange={e => handleNombreChange(e.target.value)} placeholder="Ej. Juan Pérez López"/>
        </div>
        <div className="field">
          <label className="field-label">Iniciales</label>
          <input className="input text-mono" value={form.iniciales} onChange={e => set('iniciales', e.target.value.toUpperCase().slice(0,3))} maxLength="3"/>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div className="field">
          <label className="field-label">Área *</label>
          <select className="select" value={form.area} onChange={e => set('area', e.target.value)}>
            <option value="">Seleccionar área</option>
            {AREAS.map(a => <option key={a} value={a}>{a}</option>)}
          </select>
        </div>
        <div className="field">
          <label className="field-label">Puesto *</label>
          <select className="select" value={form.puesto} onChange={e => set('puesto', e.target.value)}>
            <option value="">Seleccionar puesto</option>
            {PUESTOS.map(p => <option key={p} value={p}>{p}</option>)}
          </select>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div className="field">
          <label className="field-label">Correo electrónico</label>
          <input type="email" className="input" value={form.email} onChange={e => set('email', e.target.value)} placeholder="usuario@dominio.com"/>
        </div>
        <div className="field">
          <label className="field-label">Teléfono</label>
          <input className="input" value={form.telefono} onChange={e => set('telefono', e.target.value)} placeholder="55 1234 5678"/>
        </div>
      </div>

      <div className="detail-section-title mb-12" style={{ marginTop: 8 }}>Credenciales de acceso</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
        <div className="field">
          <label className="field-label">Usuario *</label>
          <input className="input text-mono" value={form.id} onChange={e => set('id', e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, ''))} disabled={!!usuario}/>
          {usuario && <div className="field-help">El usuario no se puede modificar</div>}
        </div>
        <div className="field">
          <label className="field-label">Password *</label>
          <div style={{ position: 'relative' }}>
            <input
              type={showPass ? 'text' : 'password'}
              className="input"
              value={form.password}
              onChange={e => set('password', e.target.value)}
              placeholder="Mín. 6 caracteres"
              style={{ paddingRight: 60 }}
            />
            <button
              type="button"
              className="text-xs"
              style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', color: 'var(--primary)', background: 'none', border: 'none', cursor: 'pointer' }}
              onClick={() => setShowPass(!showPass)}
            >
              {showPass ? 'Ocultar' : 'Mostrar'}
            </button>
          </div>
        </div>
        <div className="field">
          <label className="field-label">Confirmar password *</label>
          <input
            type={showPass ? 'text' : 'password'}
            className="input"
            value={form.confirmPassword}
            onChange={e => set('confirmPassword', e.target.value)}
          />
          {form.password && form.confirmPassword && form.password !== form.confirmPassword && (
            <div className="field-help" style={{ color: 'var(--danger)' }}>Las contraseñas no coinciden</div>
          )}
        </div>
      </div>

      <div className="detail-section-title mb-12" style={{ marginTop: 8 }}>Roles y permisos *</div>
      <div className="field-help mb-8">Selecciona los procesos a los que este usuario podrá acceder</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
        {Object.entries(APP_DATA.ROLES).map(([key, r]) => (
          <div
            key={key}
            className={`check ${form.roles.includes(key) ? 'checked' : ''}`}
            onClick={() => toggleRol(key)}
            style={{ justifyContent: 'flex-start' }}
          >
            <div className="check-box">
              {form.roles.includes(key) && <Icon name="check" size={12}/>}
            </div>
            <span style={{ fontSize: 12 }}>{r.label}</span>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 16, padding: 10, background: 'var(--primary-soft)', borderRadius: 6, fontSize: 12, color: 'var(--primary)' }}>
        💡 Al iniciar sesión, este usuario verá únicamente los módulos correspondientes a los roles marcados arriba.
      </div>
    </Modal>
  );
};




const UsuariosServer = ({ onSessionExpired }) => {
  const [state,setState]=useState({status:'loading',users:[],roles:[],error:''});
  const [editing,setEditing]=useState(null);
  const [creating,setCreating]=useState(false);
  const [query,setQuery]=useState('');
  const [message,setMessage]=useState(null);
  const [saving,setSaving]=useState(false);

  const load=async()=>{
    setState(previous=>({...previous,status:'loading',error:''}));
    try{
      const response=await window.apiRequest('users/index.php');
      setState({status:'loaded',users:response?.data?.users||[],roles:response?.data?.roles||[],error:''});
    }catch(error){
      if(error?.status===401){onSessionExpired?.();return;}
      setState(previous=>({...previous,status:'error',error:error?.message||'No fue posible cargar usuarios.'}));
    }
  };
  useEffect(()=>{load();},[]);

  const filtered=state.users.filter(user=>{
    const value=query.trim().toLowerCase();
    return !value || [user.name,user.username,user.email,(user.roles||[]).join(' ')].some(item=>String(item||'').toLowerCase().includes(value));
  });

  const save=async(form)=>{
    setSaving(true);setMessage(null);
    try{
      await window.apiRequest('users/save.php',{method:'POST',body:form});
      setEditing(null);setCreating(false);
      setMessage({tone:'success',text:form.id?'Usuario actualizado correctamente.':'Usuario creado correctamente.'});
      await load();
    }catch(error){
      if(error?.status===401){onSessionExpired?.();return;}
      setMessage({tone:'error',text:error?.message||'No fue posible guardar el usuario.'});
    }finally{setSaving(false);}
  };

  const deactivate=async(user)=>{
    if(!window.confirm(`¿Desactivar a ${user.name}? Ya no podrá iniciar sesión.`))return;
    setSaving(true);setMessage(null);
    try{
      await window.apiRequest('users/deactivate.php',{method:'POST',body:{id:Number(user.id)}});
      setEditing(null);
      setMessage({tone:'success',text:'Usuario desactivado correctamente.'});
      await load();
    }catch(error){
      if(error?.status===401){onSessionExpired?.();return;}
      setMessage({tone:'error',text:error?.message||'No fue posible desactivar el usuario.'});
    }finally{setSaving(false);}
  };

  if(state.status==='error')return <div className="card"><Empty icon="alert" title="No se pudo cargar Usuarios y perfiles" subtitle={state.error}/><div style={{textAlign:'center',paddingBottom:20}}><button className="btn btn-primary" onClick={load}>Reintentar</button></div></div>;

  return <div className="stack" data-source="users-server">
    {message&&<div role={message.tone==='success'?'status':'alert'} style={{padding:'12px 14px',borderRadius:6,background:message.tone==='success'?'#f0fdf4':'#fef2f2',color:message.tone==='success'?'#166534':'#991b1b'}}>{message.text}</div>}
    <div className="card">
      <div className="card-header"><Icon name="users" size={16}/><div><div className="card-title">Gestión de usuarios y perfiles</div><div className="card-subtitle">Datos reales de MySQL · usuarios, estado, contraseña y perfiles</div></div><div className="spacer"/><button className="btn btn-primary" onClick={()=>setCreating(true)}><Icon name="plus" size={14}/>Nuevo usuario</button></div>
      <div style={{padding:'14px 20px',borderBottom:'1px solid var(--border)',background:'var(--surface-2)'}}><input className="input" style={{maxWidth:420}} value={query} onChange={event=>setQuery(event.target.value)} placeholder="Buscar por nombre, usuario, correo o perfil..."/></div>
      <div className="table-wrap" style={{border:'none',borderRadius:0}}><table className="data"><thead><tr><th>Usuario</th><th>Nombre</th><th>Correo</th><th>Perfil principal</th><th>Perfiles asignados</th><th>Estado</th><th>Actualizado</th><th>Acción</th></tr></thead><tbody>
        {filtered.map(user=><tr key={user.id}><td><span className="text-mono">@{user.username}</span></td><td><strong>{user.name}</strong></td><td className="text-sm text-2">{user.email||'—'}</td><td>{user.role_name||'—'}</td><td><div className="row" style={{gap:4,flexWrap:'wrap'}}>{(user.roles||[]).map(code=><span key={code} className="badge" style={{background:'var(--primary-soft)',color:'var(--primary)'}}>{state.roles.find(role=>role.code===code)?.name||code}</span>)}</div></td><td><span className="status-pill" style={{background:user.status==='active'?'#dcfce7':'#f3f4f6',color:user.status==='active'?'#166534':'#4b5563'}}>{user.status==='active'?'Activo':'Inactivo'}</span></td><td className="text-sm text-2">{user.updated_at||'—'}</td><td><button className="btn btn-ghost btn-sm" onClick={()=>setEditing(user)}>Editar</button></td></tr>)}
        {!filtered.length&&<tr><td colSpan="8"><Empty icon="users" title="Sin usuarios" subtitle="No hay usuarios que coincidan con la búsqueda"/></td></tr>}
      </tbody></table></div>
    </div>
    <UsuarioServerModal open={creating||!!editing} user={editing} roles={state.roles} saving={saving} onClose={()=>{setCreating(false);setEditing(null);}} onSave={save} onDeactivate={editing?()=>deactivate(editing):null}/>
  </div>;
};

const UsuarioServerModal=({open,user,roles,saving,onClose,onSave,onDeactivate})=>{
  const empty={id:0,name:'',username:'',email:'',status:'active',password:'',confirmPassword:'',role_ids:[],primary_role_id:0};
  const [form,setForm]=useState(empty);
  const [showPassword,setShowPassword]=useState(false);
  const [error,setError]=useState('');
  useEffect(()=>{
    if(user){
      const ids=(user.roles||[]).map(code=>Number(roles.find(role=>role.code===code)?.id||0)).filter(Boolean);
      const primary=Number(roles.find(role=>role.code===user.role)?.id||ids[0]||0);
      setForm({id:Number(user.id),name:user.name||'',username:user.username||'',email:user.email||'',status:user.status||'active',password:'',confirmPassword:'',role_ids:ids,primary_role_id:primary});
    }else setForm(empty);
    setError('');setShowPassword(false);
  },[user,open,roles]);
  const set=(key,value)=>setForm(previous=>({...previous,[key]:value}));
  const toggleRole=id=>setForm(previous=>{
    const exists=previous.role_ids.includes(id);
    const role_ids=exists?previous.role_ids.filter(value=>value!==id):[...previous.role_ids,id];
    const primary_role_id=role_ids.includes(previous.primary_role_id)?previous.primary_role_id:(role_ids[0]||0);
    return {...previous,role_ids,primary_role_id};
  });
  const submit=()=>{
    if(!form.name.trim()||!form.username.trim()){setError('Nombre y usuario son obligatorios.');return;}
    if(!form.role_ids.length){setError('Selecciona al menos un perfil.');return;}
    if(!user&&form.password.length<6){setError('La contraseña debe tener al menos 6 caracteres.');return;}
    if(form.password&&form.password.length<6){setError('La nueva contraseña debe tener al menos 6 caracteres.');return;}
    if(form.password!==form.confirmPassword){setError('Las contraseñas no coinciden.');return;}
    const {confirmPassword,...payload}=form;
    onSave(payload);
  };
  return <Modal open={open} onClose={onClose} title={user?`Editar usuario · ${user.name}`:'Nuevo usuario'} maxWidth={700} footer={<><button className="btn btn-ghost" onClick={onClose} disabled={saving}>Cancelar</button>{user&&<button className="btn" style={{color:'var(--danger)',marginRight:'auto'}} onClick={onDeactivate} disabled={saving||user.status==='inactive'}>{user.status==='inactive'?'Usuario inactivo':'Desactivar usuario'}</button>}<button className="btn btn-primary" onClick={submit} disabled={saving}>{saving?'Guardando…':user?'Guardar cambios':'Crear usuario'}</button></>}>
    <div className="stack" style={{gap:12}}>{error&&<div style={{padding:10,borderRadius:6,background:'#fef2f2',color:'#991b1b'}}>{error}</div>}
      <div className="grid-2" style={{display:'grid',gap:12}}><div className="field"><label className="field-label">Nombre completo *</label><input className="input" value={form.name} onChange={event=>set('name',event.target.value)}/></div><div className="field"><label className="field-label">Usuario *</label><input className="input text-mono" value={form.username} onChange={event=>set('username',event.target.value.toLowerCase().replace(/[^a-z0-9._-]/g,''))}/></div></div>
      <div className="grid-2" style={{display:'grid',gap:12}}><div className="field"><label className="field-label">Correo</label><input type="email" className="input" value={form.email} onChange={event=>set('email',event.target.value)}/></div><div className="field"><label className="field-label">Estado</label><select className="select" value={form.status} onChange={event=>set('status',event.target.value)}><option value="active">Activo</option><option value="inactive">Inactivo</option></select></div></div>
      <div className="grid-2" style={{display:'grid',gap:12}}><div className="field"><label className="field-label">{user?'Nueva contraseña':'Contraseña *'}</label><input type={showPassword?'text':'password'} className="input" value={form.password} onChange={event=>set('password',event.target.value)} placeholder={user?'Dejar vacío para conservarla':'Mínimo 6 caracteres'}/></div><div className="field"><label className="field-label">Confirmar contraseña</label><input type={showPassword?'text':'password'} className="input" value={form.confirmPassword} onChange={event=>set('confirmPassword',event.target.value)}/><label className="text-xs text-2"><input type="checkbox" checked={showPassword} onChange={event=>setShowPassword(event.target.checked)}/> Mostrar contraseña</label></div></div>
      <div><div className="detail-section-title">Perfiles asignados *</div><div className="field-help mb-8">Marca los perfiles y selecciona cuál será el principal.</div><div style={{display:'grid',gridTemplateColumns:'repeat(3,minmax(0,1fr))',gap:8}}>{roles.map(role=><div key={role.id} className={`check ${form.role_ids.includes(Number(role.id))?'checked':''}`} onClick={()=>toggleRole(Number(role.id))}><div className="check-box">{form.role_ids.includes(Number(role.id))&&<Icon name="check" size={12}/>}</div><div style={{minWidth:0,flex:1}}><div>{role.name}</div><div className="text-xs text-3">{role.description}</div></div>{form.role_ids.includes(Number(role.id))&&<input type="radio" name="primary-role" checked={form.primary_role_id===Number(role.id)} onClick={event=>event.stopPropagation()} onChange={()=>set('primary_role_id',Number(role.id))} title="Perfil principal"/>}</div>)}</div></div>
    </div>
  </Modal>;
};

const GestionUsuarios=(props)=>window.APP_CONFIG?.AUTH?.MODE==='server'
  ? <UsuariosServer onSessionExpired={props.onSessionExpired}/>
  : <GestionUsuariosLocal {...props}/>;
Object.assign(window,{GestionUsuarios});
