// Admin panel — gestión de permisos por rol × área (matriz editable),
// usuarios y bitácora de auditoría.

const { useState: useStateAd, useMemo: useMemoAd, useEffect: useEffectAd } = React;

/* ------------------------------------------------------------------ */
/*  Helpers de permisos                                                */
/* ------------------------------------------------------------------ */
function getLevel(permissions, roleId, scopeId, fallbackScopeId = null) {
  const perms = permissions[roleId] || {};
  if (scopeId in perms) return perms[scopeId];
  if (fallbackScopeId && fallbackScopeId in perms) return perms[fallbackScopeId];
  return "none";
}
function levelInfo(permissionLevels, levelShort) {
  return permissionLevels.find(l => l.short === levelShort) || permissionLevels[0];
}

/* ------------------------------------------------------------------ */
/*  Permission pill                                                     */
/* ------------------------------------------------------------------ */
function PermPill({ level, info, onClick, mini = false, inherited = false }) {
  const isNone = level === "none";
  const isHigh = level === "admin";
  return (
    <button
      onClick={onClick}
      className={"perm-pill" + (isNone ? " none" : "") + (isHigh ? " high" : "") + (inherited ? " inherited" : "") + (mini ? " mini" : "")}
      style={{ "--c": info?.color || "#6B7280" }}
      title={`${info?.label || level} — clic para cambiar`}
    >
      <span className="dot"/>
      <span className="lbl">{mini ? (info?.short || level) : (info?.label || level)}</span>
      {inherited && !mini && <span className="inh">heredado</span>}
    </button>
  );
}

/* ------------------------------------------------------------------ */
/*  Level Editor popover                                               */
/* ------------------------------------------------------------------ */
function LevelEditor({ permissionLevels, current, onPick, onClose, anchor }) {
  if (!anchor) return null;
  const rect = anchor.getBoundingClientRect();
  return (
    <>
      <div className="pop-backdrop" onClick={onClose}/>
      <div className="pop" style={{ top: rect.bottom + 6, left: rect.left }}>
        <div className="pop-title">Cambiar nivel de acceso</div>
        {permissionLevels.map(l => (
          <button
            key={l.id}
            className={"pop-item" + (current === l.short ? " active" : "")}
            onClick={() => onPick(l.short)}
          >
            <span className="pop-dot" style={{ background: l.color }}/>
            <div style={{flex:1, textAlign:"left"}}>
              <div className="pop-lbl">{l.label}</div>
              <div className="pop-desc">{l.desc}</div>
            </div>
            {current === l.short && <Icon name="check" size={14} style={{color: "var(--green)"}}/>}
          </button>
        ))}
      </div>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Admin shell                                                        */
/* ------------------------------------------------------------------ */
function AdminPanel({ sections, allFolders, roles, areas, users: initialUsers, permissionLevels, currentUser, onLogout, onBackToLibrary }) {
  const [tab, setTab]           = useStateAd("roles");
  const [permissions, setPerms] = useStateAd({});
  const [loadingPerms, setLoadingPerms] = useStateAd(false);
  const [openRole, setOpenRole] = useStateAd(null);
  const [editor, setEditor]     = useStateAd(null);
  const [query, setQuery]       = useStateAd("");
  const [toast, setToast]       = useStateAd(null);
  const [users, setUsers]       = useStateAd(initialUsers || []);

  const showToast = function(msg) {
    setToast(msg);
    setTimeout(() => setToast(null), 2000);
  };

  // Cargar permisos de todos los roles
  useEffectAd(() => {
    if (!roles.length) return;
    setLoadingPerms(true);
    Promise.all(roles.map(r => API.Permissions.matrix(r.id)))
      .then(function(matrices) {
        const merged = {};
        roles.forEach(function(r, i) {
          const matrix = matrices[i]?.matrix || [];
          merged[r.id] = {};
          matrix.forEach(function(entry) {
            merged[r.id][entry.scope_id] = entry.level;
            (entry.folders || []).forEach(function(f) {
              if (f.level !== null) {
                merged[r.id][f.scope_id] = f.level;
              }
            });
          });
        });
        setPerms(merged);
      })
      .catch(function() {})
      .finally(function() { setLoadingPerms(false); });
  }, [roles]);

  const setLevel = async function(roleId, scopeId, levelShort, scopeType) {
    // Actualización optimista
    setPerms(function(prev) {
      return Object.assign({}, prev, {
        [roleId]: Object.assign({}, prev[roleId] || {}, { [scopeId]: levelShort }),
      });
    });

    try {
      await API.Permissions.patch({
        role_id:    roleId,
        scope_type: scopeType || 'section',
        scope_id:   scopeId,
        level:      levelShort,
      });
      const info = levelInfo(permissionLevels, levelShort);
      showToast("Permiso actualizado: " + (info?.label || levelShort));
    } catch(err) {
      showToast("Error al guardar permiso");
    }
  };

  return (
    <div className="app-shell" data-screen-label="03 Administración">
      <AdminSidebar
        sections={sections}
        areas={areas}
        roles={roles}
        users={users}
        currentUser={currentUser}
        tab={tab}
        setTab={setTab}
        onLogout={onLogout}
        onBackToLibrary={onBackToLibrary}
      />

      <div className="main">
        <div className="topbar">
          <div className="search">
            <Icon name="search" size={16} style={{color:"var(--muted)"}}/>
            <input value={query} onChange={(e)=>setQuery(e.target.value)} placeholder="Buscar rol, usuario o área…"/>
            <span className="kbd">⌘ K</span>
          </div>
          <div className="topbar-actions">
            <button className="icon-btn" title="Notificaciones"><Icon name="bell" size={17}/></button>
            <button className="icon-btn" title="Ajustes"><Icon name="settings" size={17}/></button>
            <div className="divider-vert"/>
            <button className="btn ghost"><Icon name="plus" size={14}/> Nuevo usuario</button>
            <button className="btn green"><Icon name="plus" size={14}/> Nuevo rol</button>
          </div>
        </div>

        <div className="content">
          <div className="crumbs">
            <span>Biblioteca</span>
            <Icon name="chevron" size={12} className="sep"/>
            <span>Administración</span>
            <Icon name="chevron" size={12} className="sep"/>
            <span className="now">
              {tab === "roles" ? "Roles y permisos" : tab === "usuarios" ? "Usuarios" : "Bitácora de auditoría"}
            </span>
          </div>

          <div className="page-head">
            <div>
              <div className="eyebrow" style={{marginBottom: 10}}>Panel de administración</div>
              <h1 className="h-title">Control de acceso</h1>
              <p className="subtitle h-sub">Define qué áreas y archivos puede ver, editar o administrar cada rol del sistema.</p>
            </div>
            <div className="h-meta">
              <div><div>Roles</div><b>{roles.length}</b></div>
              <div><div>Usuarios</div><b>{users.length.toLocaleString("es-MX")}</b></div>
              <div><div>Áreas</div><b>{areas.length}</b></div>
            </div>
          </div>

          {/* Tabs */}
          <div className="admin-tabs">
            <button className={"adm-tab" + (tab==="roles"?" active":"")}    onClick={()=>setTab("roles")}>Roles y permisos</button>
            <button className={"adm-tab" + (tab==="usuarios"?" active":"")} onClick={()=>setTab("usuarios")}>Usuarios <span className="badge-num">{users.length}</span></button>
            <button className={"adm-tab" + (tab==="auditoria"?" active":"")}onClick={()=>setTab("auditoria")}>Auditoría</button>
          </div>

          {tab === "roles" && (
            loadingPerms
              ? <div style={{color:"var(--muted)", fontSize:13, padding:"24px 0"}}>Cargando permisos…</div>
              : <RolesView
                  sections={sections}
                  allFolders={allFolders}
                  roles={roles}
                  permissions={permissions}
                  permissionLevels={permissionLevels}
                  query={query}
                  onCellClick={(roleId, scopeId, scopeType, anchor) => setEditor({ roleId, scopeId, scopeType, anchor })}
                  openRole={openRole}
                  setOpenRole={setOpenRole}
                />
          )}

          {tab === "usuarios" && (
            <UsersView
              users={users}
              roles={roles}
              areas={areas}
              query={query}
              onUpdate={function(updatedUser) {
                setUsers(function(prev) {
                  return prev.map(function(u) { return u.id === updatedUser.id ? updatedUser : u; });
                });
              }}
              showToast={showToast}
            />
          )}

          {tab === "auditoria" && <AuditView/>}
        </div>
      </div>

      {/* Popover editor */}
      {editor && (
        <LevelEditor
          permissionLevels={permissionLevels}
          current={getLevel(permissions, editor.roleId, editor.scopeId)}
          onPick={function(lvl) {
            setLevel(editor.roleId, editor.scopeId, lvl, editor.scopeType);
            setEditor(null);
          }}
          onClose={() => setEditor(null)}
          anchor={editor.anchor}
        />
      )}

      {toast && (
        <div style={{
          position:"fixed", bottom:24, left:"50%", transform:"translateX(-50%)",
          background:"var(--ink)", color:"#fff", padding:"12px 18px",
          fontSize:13, borderRadius: 6, boxShadow:"var(--shadow-pop)", zIndex: 100,
          display:"flex", alignItems:"center", gap:10,
        }}>
          <Icon name="check" size={14} style={{color:"var(--green)"}}/>
          {toast}
        </div>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Admin sidebar                                                      */
/* ------------------------------------------------------------------ */
function AdminSidebar({ sections, areas, roles, users, currentUser, tab, setTab, onLogout, onBackToLibrary }) {
  return (
    <aside className="sidebar" data-screen-label="Admin sidebar">
      <div className="sidebar-brand">
        <div className="brand-mark">B</div>
        <div>
          <div className="brand-name">Biblioteca</div>
          <div className="brand-sub">Administración</div>
        </div>
      </div>

      <div className="sidebar-section">
        <div className="eyebrow">Volver</div>
        <div className="nav-item" onClick={onBackToLibrary}>
          <Icon name="arrowRight" size={17} style={{transform:"rotate(180deg)"}}/>
          <span>Acervo</span>
        </div>
      </div>

      <div className="sidebar-section">
        <div className="eyebrow">Acceso</div>
        <div className={"nav-item" + (tab==="roles"?" active":"")}    onClick={()=>setTab("roles")}>
          <Icon name="lock" size={17}/><span>Roles y permisos</span><span className="count">{roles.length}</span>
        </div>
        <div className={"nav-item" + (tab==="usuarios"?" active":"")} onClick={()=>setTab("usuarios")}>
          <Icon name="user" size={17}/><span>Usuarios</span><span className="count">{users.length}</span>
        </div>
        <div className={"nav-item" + (tab==="auditoria"?" active":"")}onClick={()=>setTab("auditoria")}>
          <Icon name="clock" size={17}/><span>Auditoría</span>
        </div>
      </div>

      <div className="sidebar-section">
        <div className="eyebrow">Áreas</div>
        {areas.map(a => (
          <div key={a.id} className="nav-item" style={{cursor: "default"}}>
            <span className="dot" style={{width:6, height:6, borderRadius:50, background:"#6E6D68"}}/>
            <span>{a.name}</span>
            <span className="count">{a.members_count || 0}</span>
          </div>
        ))}
      </div>

      <div className="sidebar-foot">
        <div className="avatar" style={{background: currentUser?.avatar_color || "#374151"}}>
          {currentUser?.initials || "U"}
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div className="user-name">{currentUser?.name || "Usuario"}</div>
          <div className="user-role">{currentUser?.role?.name || ""}</div>
        </div>
        <button className="icon-btn" style={{color:"#8A8A86"}} title="Cerrar sesión" onClick={onLogout}>
          <Icon name="logout" size={16}/>
        </button>
      </div>
    </aside>
  );
}

/* ------------------------------------------------------------------ */
/*  Vista: Roles × Secciones (matriz)                                  */
/* ------------------------------------------------------------------ */
function RolesView({ sections, allFolders, roles, permissions, permissionLevels, query, onCellClick, openRole, setOpenRole }) {
  const q = query.toLowerCase().trim();
  const filteredRoles = q
    ? roles.filter(r => r.name.toLowerCase().includes(q) || (r.description||"").toLowerCase().includes(q))
    : roles;

  return (
    <>
      {/* Leyenda */}
      <div className="legend">
        <div className="legend-title">Niveles de acceso</div>
        {permissionLevels.map(l => (
          <div key={l.id} className="legend-item">
            <span className="legend-dot" style={{background: l.color}}/>
            <div>
              <div className="legend-lbl">{l.label}</div>
              <div className="legend-desc">{l.desc}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="section-label">
        <span className="lbl">Matriz: roles × secciones</span>
        <span className="ln"/>
        <span className="meta">{filteredRoles.length} roles · {sections.length} secciones</span>
      </div>

      <div className="perm-matrix">
        <div className="pm-head">
          <div className="pm-cell pm-corner">Rol / Sección</div>
          {sections.map(s => (
            <div key={s.id} className="pm-cell pm-col-head">
              <div style={{display:"flex", alignItems:"center", gap:8}}>
                <Icon name={s.icon} size={14}/>
                <span>{s.label}</span>
              </div>
              <div className="pm-col-count">{(s.items_count||0).toLocaleString("es-MX")} archivos</div>
            </div>
          ))}
          <div className="pm-cell pm-col-head" style={{textAlign:"right"}}>Detalle</div>
        </div>

        {filteredRoles.map(role => (
          <React.Fragment key={role.id}>
            <div className={"pm-row" + (openRole === role.id ? " expanded" : "")}>
              <div className="pm-cell pm-role">
                <span className="role-bar" style={{background: role.color}}/>
                <div>
                  <div className="role-name">{role.name}{role.system && <span className="sys">SISTEMA</span>}</div>
                  <div className="role-desc">{role.description}</div>
                  <div className="role-meta">{role.members_count || 0} {(role.members_count||0) === 1 ? "usuario" : "usuarios"}</div>
                </div>
              </div>

              {sections.map(s => {
                const level = getLevel(permissions, role.id, s.id);
                const info  = levelInfo(permissionLevels, level);
                return (
                  <div key={s.id} className="pm-cell">
                    <PermPill
                      level={level}
                      info={info}
                      onClick={(e) => onCellClick(role.id, s.id, 'section', e.currentTarget)}
                    />
                  </div>
                );
              })}

              <div className="pm-cell" style={{justifyContent:"flex-end", display:"flex"}}>
                <button
                  className="btn ghost sm"
                  onClick={() => setOpenRole(openRole === role.id ? null : role.id)}
                >
                  {openRole === role.id ? "Cerrar" : "Carpetas"}
                  <Icon name={openRole === role.id ? "chevronDown" : "chevron"} size={12}/>
                </button>
              </div>
            </div>

            {openRole === role.id && (
              <div className="pm-detail">
                {sections.map(s => {
                  const sectionFolders = allFolders[s.id] || [];
                  return (
                    <div key={s.id} className="pm-detail-block">
                      <div className="pm-detail-head">
                        <div style={{display:"flex", alignItems:"center", gap:8}}>
                          <Icon name={s.icon} size={14}/>
                          <span style={{fontFamily:"var(--font-display)", fontWeight:700, fontSize:13}}>{s.label}</span>
                        </div>
                        <span className="mono">
                          Por defecto · {levelInfo(permissionLevels, getLevel(permissions, role.id, s.id))?.label || "Sin acceso"}
                        </span>
                      </div>
                      <div className="pm-folders">
                        {sectionFolders.map(f => {
                          const inherited = !((permissions[role.id] || {})[f.id]);
                          const level = getLevel(permissions, role.id, f.id, s.id);
                          const info  = levelInfo(permissionLevels, level);
                          return (
                            <div key={f.id} className="pm-folder">
                              <span className="pm-folder-bar" style={{background: f.color}}/>
                              <div style={{flex:1, minWidth:0}}>
                                <div className="pm-folder-name">{f.name}</div>
                                <div className="pm-folder-meta">{f.items_count || 0} elementos</div>
                              </div>
                              <PermPill
                                level={level}
                                info={info}
                                mini
                                inherited={inherited}
                                onClick={(e) => onCellClick(role.id, f.id, 'folder', e.currentTarget)}
                              />
                            </div>
                          );
                        })}
                        {sectionFolders.length === 0 && (
                          <div style={{color:"var(--muted)", fontSize:12, padding:"8px 0"}}>Sin carpetas en esta sección</div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </React.Fragment>
        ))}
      </div>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Vista: Usuarios                                                    */
/* ------------------------------------------------------------------ */
function UsersView({ users, roles, areas, query, onUpdate, showToast }) {
  const q = query.toLowerCase().trim();
  const filtered = q
    ? users.filter(u => u.name.toLowerCase().includes(q) || u.email.toLowerCase().includes(q))
    : users;

  const handleStatusChange = async function(user) {
    const newStatus = user.status === 'active' ? 'disabled' : 'active';
    try {
      const updated = await API.Users.update(user.id, { status: newStatus });
      onUpdate(updated);
      showToast("Estado actualizado: " + (newStatus === 'active' ? 'Activo' : 'Desactivado'));
    } catch(e) {
      showToast("Error al actualizar usuario");
    }
  };

  return (
    <>
      <div className="section-label">
        <span className="lbl">Usuarios del sistema</span>
        <span className="ln"/>
        <span className="meta">{filtered.length} cuentas</span>
      </div>

      <div className="list">
        <div className="row head" style={{gridTemplateColumns: "36px 1.6fr 1fr 1fr 0.9fr 0.6fr 80px"}}>
          <div></div>
          <div>Usuario</div>
          <div>Rol</div>
          <div>Área</div>
          <div>Última actividad</div>
          <div>Estado</div>
          <div></div>
        </div>
        {filtered.map(u => {
          const role = roles.find(r => r.id === (u.role?.id || u.role_id));
          const area = areas.find(a => a.id === (u.area?.id || u.area_id));
          const lastActive = u.last_active_at
            ? new Date(u.last_active_at).toLocaleDateString("es-MX", {day:"2-digit",month:"short",year:"numeric"})
            : "Nunca";
          return (
            <div className="row" key={u.id} style={{gridTemplateColumns: "36px 1.6fr 1fr 1fr 0.9fr 0.6fr 80px"}}>
              <div className="avatar" style={{width:32, height:32, fontSize:11, background: u.avatar_color || role?.color || "#1B1A1A"}}>
                {u.initials || u.name.split(" ").map(n=>n[0]).slice(0,2).join("")}
              </div>
              <div>
                <div className="nm">{u.name}</div>
                <div className="sub">{u.email}</div>
              </div>
              <div className="tabular">{role?.name || u.role?.name || "—"}</div>
              <div className="tabular">{area?.name || u.area?.name || "—"}</div>
              <div className="tabular">{lastActive}</div>
              <div>
                <span className={"status-pill " + u.status}>
                  {u.status === "active" ? "Activo" : u.status === "pending" ? "Pendiente" : "Inactivo"}
                </span>
              </div>
              <div>
                <button className="dl" title="Cambiar estado" onClick={() => handleStatusChange(u)}>
                  <Icon name="settings" size={14}/>
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Vista: Auditoría (carga desde API)                                 */
/* ------------------------------------------------------------------ */
function AuditView() {
  const [entries, setEntries] = useStateAd([]);
  const [loading, setLoading] = useStateAd(true);
  const [total, setTotal]     = useStateAd(0);

  useEffectAd(() => {
    API.Audit.list({ per_page: 50 })
      .then(function(res) {
        setEntries(res.data || []);
        setTotal(res.total || 0);
      })
      .catch(function() {})
      .finally(function() { setLoading(false); });
  }, []);

  const handleExport = function() {
    window.open(API.Audit.exportCsvUrl(), "_blank");
  };

  if (loading) {
    return <div style={{color:"var(--muted)", fontSize:13, padding:"24px 0"}}>Cargando auditoría…</div>;
  }

  return (
    <>
      <div className="section-label">
        <span className="lbl">Bitácora de cambios</span>
        <span className="ln"/>
        <span className="meta">{total} eventos en total</span>
        <button className="btn ghost sm" onClick={handleExport} style={{marginLeft:"auto"}}>
          <Icon name="download" size={12}/> Exportar CSV
        </button>
      </div>

      <div className="audit">
        {entries.length === 0 && (
          <div style={{color:"var(--muted)", fontSize:13, padding:"16px 0"}}>Sin eventos registrados.</div>
        )}
        {entries.map(function(e) {
          return (
            <div key={e.id} className="audit-row">
              <div className="audit-time mono">{e.ts}</div>
              <div className="audit-dot"/>
              <div className="audit-body">
                <div className="audit-line">
                  <b>{e.actor?.name || "Sistema"}</b> · {e.action}
                  {e.target_label && <span className="audit-tgt"> {e.target_label}</span>}
                </div>
                {(e.from_value || e.to_value) && (
                  <div className="audit-change">
                    {e.from_value && <span className="audit-from">{e.from_value}</span>}
                    {e.from_value && e.to_value && <Icon name="arrowRight" size={12}/>}
                    {e.to_value && <span className="audit-to">{e.to_value}</span>}
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}

window.AdminPanel = AdminPanel;
